deserialize non-prefixed stuint (#10)

This commit is contained in:
Eric 2024-02-14 15:40:32 +11:00 committed by GitHub
parent 956d4a2e57
commit a2cca7788b
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 23 additions and 2 deletions

View File

@ -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)

View File

@ -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)