Coverage for an_website / patches / json.py: 29.167%
48 statements
« prev ^ index » next coverage.py v7.13.5, created at 2026-04-24 17:35 +0000
« prev ^ index » next coverage.py v7.13.5, created at 2026-04-24 17:35 +0000
1# This program is free software: you can redistribute it and/or modify
2# it under the terms of the GNU Affero General Public License as
3# published by the Free Software Foundation, either version 3 of the
4# License, or (at your option) any later version.
5#
6# This program is distributed in the hope that it will be useful,
7# but WITHOUT ANY WARRANTY; without even the implied warranty of
8# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
9# GNU Affero General Public License for more details.
10#
11# You should have received a copy of the GNU Affero General Public License
12# along with this program. If not, see <https://www.gnu.org/licenses/>.
14"""A very fast JSON implementation."""
16import inspect
17from collections.abc import Callable
18from json.encoder import JSONEncoder
19from typing import IO, Any, Protocol, TypeVar
21import orjson
22import regex
24T_co = TypeVar("T_co", covariant=True)
27class SupportsRead(Protocol[T_co]): # noqa: D101
28 # pylint: disable=missing-class-docstring, too-few-public-methods
29 def read(self, __length: int = ...) -> T_co: # noqa: D102
30 # pylint: disable=missing-function-docstring
31 ...
34def get_caller_name() -> None | str: # noqa: D103
35 # pylint: disable=missing-function-docstring
36 try:
37 frame = inspect.currentframe()
38 frame = frame.f_back if frame else None
39 if not (frame and "__name__" in frame.f_globals):
40 return None
41 name = frame.f_globals["__name__"]
42 while ( # pylint: disable=while-used
43 frame and frame.f_globals.get("__name__") == name # type: ignore[truthy-bool] # noqa: B950
44 ):
45 frame = frame.f_back
46 caller = frame.f_globals.get("__name__") if frame else None
47 finally:
48 del frame
49 return caller
52def dumps( # noqa: D103 # pylint: disable=too-many-arguments
53 obj: Any,
54 *,
55 skipkeys: bool = False,
56 ensure_ascii: bool = True,
57 check_circular: bool = True,
58 allow_nan: bool = True,
59 cls: None | type[JSONEncoder] = None,
60 indent: None | int | str = None,
61 separators: None | tuple[str, str] = None,
62 default: None | Callable[[Any], Any] = None,
63 sort_keys: bool = False,
64 **kwargs: Any,
65) -> str:
66 # pylint: disable=missing-function-docstring
67 output: str | bytes
68 caller = get_caller_name()
69 option = orjson.OPT_SERIALIZE_NUMPY
70 if caller == "tornado.escape":
71 option |= orjson.OPT_NAIVE_UTC | orjson.OPT_UTC_Z
72 else:
73 option |= orjson.OPT_PASSTHROUGH_DATACLASS
74 if sort_keys:
75 option |= orjson.OPT_SORT_KEYS
76 if indent is not None:
77 option |= orjson.OPT_INDENT_2
78 if cls is not None:
79 _ = cls(
80 skipkeys=skipkeys,
81 ensure_ascii=ensure_ascii,
82 check_circular=check_circular,
83 allow_nan=allow_nan,
84 indent=indent,
85 separators=separators,
86 default=default,
87 sort_keys=sort_keys,
88 **kwargs,
89 )
90 default = _.default
91 output = orjson.dumps(obj, default, option)
92 if indent not in {None, 2, " "}:
93 if isinstance(indent, int):
94 indent = " " * indent
95 indent_bytes = str(indent).encode("UTF-8")
96 output = regex.sub(
97 rb"(?m)^\s+",
98 lambda match: len(match[0]) // 2 * indent_bytes,
99 output,
100 )
101 return output.decode("UTF-8")
104def dump(obj: Any, fp: IO[str], **kwargs: Any) -> None: # noqa: D103
105 # pylint: disable=missing-function-docstring
106 fp.write(dumps(obj, **kwargs))
109def loads(s: str | bytes, **kwargs: Any) -> Any: # noqa: D103
110 # pylint: disable=missing-function-docstring, unused-argument
111 return orjson.loads(s)
114def load(fp: SupportsRead[str | bytes], **kwargs: Any) -> Any: # noqa: D103
115 # pylint: disable=missing-function-docstring, unused-argument
116 return loads(fp.read())