diff --git a/json5/lib.py b/json5/lib.py index ecf375a..d8a1de4 100644 --- a/json5/lib.py +++ b/json5/lib.py @@ -349,6 +349,8 @@ def parse( if not s: return None, 'Empty strings are not legal JSON5', 0 start = start or 0 + if not 0 <= start <= len(s): + return None, f'Invalid start position {start}', 0 parser = Parser(s, '', pos=start) ast, err, pos = parser.parse( global_vars={'_strict': strict, '_consume_trailing': consume_trailing} diff --git a/tests/lib_test.py b/tests/lib_test.py index fa85e7e..8487614 100644 --- a/tests/lib_test.py +++ b/tests/lib_test.py @@ -549,6 +549,16 @@ def test_parse_empty_input(self): (None, 'Empty strings are not legal JSON5', 0), ) + def test_parse_invalid_start(self): + # A negative start indexes the string from the end and a start past + # the end indexes off it; neither is an offset into the document. + for source, start in (('012', -2), ('012', 4)): + with self.subTest(source=source, start=start): + self.assertEqual( + json5.parse(source, start=start), + (None, f'Invalid start position {start}', 0), + ) + def test_parse(self): self.check('4', 4, err=None, pos=1) self.check('4 ', 4, err=None, pos=2)