From a2cca7788b4764e306b16a7d0c0ececff31a8ed0 Mon Sep 17 00:00:00 2001 From: Eric <5089238+emizzle@users.noreply.github.com> Date: Wed, 14 Feb 2024 15:40:32 +1100 Subject: [PATCH] deserialize non-prefixed stuint (#10) --- serde/json/deserializer.nim | 5 +++-- tests/json/testDeserialize.nim | 20 ++++++++++++++++++++ 2 files changed, 23 insertions(+), 2 deletions(-) diff --git a/serde/json/deserializer.nim b/serde/json/deserializer.nim index 72d6896..72e5181 100644 --- a/serde/json/deserializer.nim +++ b/serde/json/deserializer.nim @@ -126,10 +126,11 @@ proc fromJson*[N: static[int], T: array[N, byte]](_: type T, json: JsonNode): ?! proc fromJson*[T: distinct](_: type T, json: JsonNode): ?!T = success T(?T.distinctBase.fromJson(json)) -proc fromJson*[N: static[int], T: StUint[N]](_: type T, json: JsonNode): ?!T = +proc fromJson*(T: typedesc[StUint or StInt], json: JsonNode): ?!T = expectJsonKind(T, JString, json) let jsonStr = json.getStr - let prefix = jsonStr[0 .. 1].toLowerAscii + let prefix = if jsonStr.len >= 2: jsonStr[0 .. 1].toLowerAscii + else: jsonStr case prefix of "0x": catch parse(jsonStr, T, 16) diff --git a/tests/json/testDeserialize.nim b/tests/json/testDeserialize.nim index 2a689e1..a17fdb9 100644 --- a/tests/json/testDeserialize.nim +++ b/tests/json/testDeserialize.nim @@ -19,10 +19,30 @@ suite "json serialization - deserialize": let json = newJString("Second") check !MyEnum.fromJson(json) == Second + test "deserializes UInt256 with no prefix": + let json = newJString("1") + check !UInt256.fromJson(json) == 1.u256 + + test "deserializes UInt256 from hex string representation": + let json = newJString("0x1") + check !UInt256.fromJson(json) == 0x1.u256 + + test "deserializes UInt256 from octal string representation": + let json = newJString("0o1") + check !UInt256.fromJson(json) == 0o1.u256 + + test "deserializes UInt256 from binary string representation": + let json = newJString("0b1") + check !UInt256.fromJson(json) == 0b1.u256 + test "deserializes UInt256 from non-hex string representation": let json = newJString("100000") check !UInt256.fromJson(json) == 100000.u256 + test "deserializes Int256 with no prefix": + let json = newJString("1") + check !Int256.fromJson(json) == 1.i256 + test "deserializes Option[T] when has a value": let json = newJInt(1) check (!fromJson(?int, json) == some 1)