From 6eadb6e939ffa7882ff5437033c11a9464d3385c Mon Sep 17 00:00:00 2001 From: Jacek Sieka Date: Sat, 19 Oct 2024 11:28:17 +0200 Subject: [PATCH] check length before converting to range type (#102) The index type of an array is a `range` meaning that converting an out-of-bounds value to it will raise a `Defect`. This PR fixes the defect but does nothing for arrays which are not "full" - probably, this should become an error. * bump version --- json_serialization.nimble | 2 +- json_serialization/reader_impl.nim | 8 ++++---- tests/test_reader.nim | 9 +++++++++ 3 files changed, 14 insertions(+), 5 deletions(-) diff --git a/json_serialization.nimble b/json_serialization.nimble index ef00b6b..48459a1 100644 --- a/json_serialization.nimble +++ b/json_serialization.nimble @@ -10,7 +10,7 @@ mode = ScriptMode.Verbose packageName = "json_serialization" -version = "0.2.8" +version = "0.2.9" author = "Status Research & Development GmbH" description = "Flexible JSON serialization not relying on run-time type information" license = "Apache License 2.0" diff --git a/json_serialization/reader_impl.nim b/json_serialization/reader_impl.nim index b4cd801..f4574b3 100644 --- a/json_serialization/reader_impl.nim +++ b/json_serialization/reader_impl.nim @@ -312,11 +312,11 @@ proc readValue*[T](r: var JsonReader, value: var T) elif value is array: type IDX = typeof low(value) r.parseArray(idx): - let i = IDX(idx + low(value).int) - if i <= high(value): - # TODO: dont's ask. this makes the code compile - if false: value[i] = value[i] + if idx < value.len: + let i = IDX(idx + low(value).int) readValue(r, value[i]) + else: + r.raiseUnexpectedValue("Too many items for " & $(typeof(value))) elif value is (object or tuple): mixin flavorUsesAutomaticObjectSerialization diff --git a/tests/test_reader.nim b/tests/test_reader.nim index 52f79ce..9c84170 100644 --- a/tests/test_reader.nim +++ b/tests/test_reader.nim @@ -211,3 +211,12 @@ suite "JsonReader basic test": var z = toReaderNullFields("""{"something":null,"bool":999,"string":100}""") check execReadObject(z) == 2 + + test "readValue of array": + var r = toReader "[false, true, false]" + check r.readValue(array[3, bool]) == [false, true, false] + + test "readValue of array error": + var r = toReader "[false, true, false]" + expect JsonReaderError: + discard r.readValue(array[2, bool])