|
1 | 1 | """Canonical encoding for the JSONSchema semantics, where 1 == 1.0."""
|
2 | 2 | import json
|
3 | 3 | import math
|
4 |
| -from json.encoder import _make_iterencode, encode_basestring_ascii # type: ignore |
| 4 | +import platform |
5 | 5 | from typing import Any, Dict, Tuple, Union
|
6 | 6 |
|
7 | 7 | # Mypy does not (yet!) support recursive type definitions.
|
8 | 8 | # (and writing a few steps by hand is a DoS attack on the AST walker in Pytest)
|
| 9 | +PYTHON_IMPLEMENTATION = platform.python_implementation() |
9 | 10 | JSONType = Union[None, bool, float, str, list, Dict[str, Any]]
|
10 | 11 |
|
| 12 | +if PYTHON_IMPLEMENTATION != "PyPy": |
| 13 | + from json.encoder import _make_iterencode, encode_basestring_ascii # type: ignore |
| 14 | +else: |
| 15 | + _make_iterencode = None |
| 16 | + encode_basestring_ascii = None |
| 17 | + |
| 18 | + |
| 19 | +def _floatstr(o: float) -> str: |
| 20 | + # This is the bit we're overriding - integer-valued floats are |
| 21 | + # encoded as integers, to support JSONschemas's uniqueness. |
| 22 | + assert math.isfinite(o) |
| 23 | + if o == int(o): |
| 24 | + return repr(int(o)) |
| 25 | + return repr(o) |
| 26 | + |
11 | 27 |
|
12 | 28 | class CanonicalisingJsonEncoder(json.JSONEncoder):
|
13 |
| - def iterencode(self, o: Any, _one_shot: bool = False) -> Any: |
14 |
| - """Replace a stdlib method, so we encode integer-valued floats as ints.""" |
15 |
| - |
16 |
| - def floatstr(o: float) -> str: |
17 |
| - # This is the bit we're overriding - integer-valued floats are |
18 |
| - # encoded as integers, to support JSONschemas's uniqueness. |
19 |
| - assert math.isfinite(o) |
20 |
| - if o == int(o): |
21 |
| - return repr(int(o)) |
22 |
| - return repr(o) |
23 |
| - |
24 |
| - return _make_iterencode( |
25 |
| - {}, |
26 |
| - self.default, |
27 |
| - encode_basestring_ascii, |
28 |
| - self.indent, |
29 |
| - floatstr, |
30 |
| - self.key_separator, |
31 |
| - self.item_separator, |
32 |
| - self.sort_keys, |
33 |
| - self.skipkeys, |
34 |
| - _one_shot, |
35 |
| - )(o, 0) |
| 29 | + |
| 30 | + if PYTHON_IMPLEMENTATION == "PyPy": |
| 31 | + |
| 32 | + def _JSONEncoder__floatstr(self, o: float) -> str: # noqa: N802 |
| 33 | + return _floatstr(o) |
| 34 | + |
| 35 | + else: |
| 36 | + |
| 37 | + def iterencode(self, o: Any, _one_shot: bool = False) -> Any: |
| 38 | + """Replace a stdlib method, so we encode integer-valued floats as ints.""" |
| 39 | + return _make_iterencode( |
| 40 | + {}, |
| 41 | + self.default, |
| 42 | + encode_basestring_ascii, |
| 43 | + self.indent, |
| 44 | + _floatstr, |
| 45 | + self.key_separator, |
| 46 | + self.item_separator, |
| 47 | + self.sort_keys, |
| 48 | + self.skipkeys, |
| 49 | + _one_shot, |
| 50 | + )(o, 0) |
36 | 51 |
|
37 | 52 |
|
38 | 53 | def encode_canonical_json(value: JSONType) -> str:
|
|
0 commit comments