Skip to content

Commit 665675c

Browse files
author
Nathan Gillett
committed
Fix JCS canon whitespace decode, int overflow, and B904
Decode JSON after lstrip with idx adjusted for trailing checks; map float(i) OverflowError to ValueError for huge ints; chain ValueError from _NotJSON; extend number tests for whitespace-wrapped JSON. Signed-off-by: Nathan Gillett <intentproof@gmail.com>
1 parent 46781a5 commit 665675c

2 files changed

Lines changed: 11 additions & 4 deletions

File tree

src/intentproof/canon.py

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -127,7 +127,10 @@ def _format_es6(f: float) -> str:
127127
def _encode_int(i: int) -> str:
128128
if -(2 ** 53) <= i <= 2 ** 53:
129129
return str(i)
130-
f = float(i)
130+
try:
131+
f = float(i)
132+
except OverflowError as e:
133+
raise ValueError(f"out of range integer {i}") from e
131134
if math.isinf(f):
132135
raise ValueError(f"out of range integer {i}")
133136
return _format_es6(f)
@@ -206,10 +209,12 @@ def _object_pairs_hook(pairs: list[tuple[str, Any]]) -> _CanonObject:
206209
parse_constant=lambda c: (_ for _ in ()).throw(ValueError(f"non-finite number {c}")),
207210
object_pairs_hook=_object_pairs_hook,
208211
)
212+
stripped = s.lstrip()
209213
try:
210-
value, idx = decoder.raw_decode(s)
214+
value, idx = decoder.raw_decode(stripped)
211215
except json.JSONDecodeError as exc:
212216
raise _NotJSON from exc
217+
idx += len(s) - len(stripped)
213218
if s[idx:].strip():
214219
raise ValueError("trailing data after JSON value")
215220
return value
@@ -230,9 +235,9 @@ def canonicalize(obj: Any) -> str:
230235
if first in '{"[-tfnNI' or first.isdigit():
231236
try:
232237
tree = _decode_json(obj)
233-
except _NotJSON:
238+
except _NotJSON as e:
234239
if any(ch in stripped for ch in '{}[]:,'):
235-
raise ValueError("invalid JSON")
240+
raise ValueError("invalid JSON") from e
236241
return _encode_string(obj)
237242
return _encode_value(tree)
238243
return _encode_string(obj)

tests/test_canon.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -82,6 +82,8 @@ def test_number_cases(self):
8282
("0", "0"),
8383
("-0", "0"),
8484
("1", "1"),
85+
(" 1 ", "1"),
86+
("\n1\t", "1"),
8587
("-1", "-1"),
8688
("1.0", "1"),
8789
("1.5", "1.5"),

0 commit comments

Comments
 (0)