Skip to content

Commit

Permalink
x.json2: fix panic on calling json2.decode of an optional enum (fix #…
Browse files Browse the repository at this point in the history
  • Loading branch information
pierrec committed Jan 21, 2024
1 parent 3e8c535 commit d585e50
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 3 deletions.
20 changes: 20 additions & 0 deletions vlib/x/json2/decode_struct_test.v
Expand Up @@ -105,4 +105,24 @@ fn test_types() {
} else {
assert true
}

assert json.decode[StructType[Enumerates]]('{"val": 0}')!.val == .a
assert json.decode[StructType[Enumerates]]('{"val": 1}')!.val == .b
assert json.decode[StructType[Enumerates]]('{"val": 99}')!.val == .e
assert json.decode[StructType[Enumerates]]('{}')!.val == .a

if x := json.decode[StructTypeOption[Enumerates]]('{"val": 0}')!.val {
assert x == .a
}
if x := json.decode[StructTypeOption[Enumerates]]('{"val": 1}')!.val {
assert x == .b
}
if x := json.decode[StructTypeOption[Enumerates]]('{"val": 99}')!.val {
assert x == .e
}
if x := json.decode[StructTypeOption[Enumerates]]('{}')!.val {
assert false
} else {
assert true
}
}
8 changes: 5 additions & 3 deletions vlib/x/json2/json2.v
Expand Up @@ -37,10 +37,12 @@ fn decode_struct[T](_ T, res map[string]Any) !T {
}

$if field.is_enum {
typ.$(field.name) = if key := res[field.name] {
key.int()
if v := res[json_name] {
typ.$(field.name) = v.int()
} else {
res[json_name]!.int()
$if field.is_option {
typ.$(field.name) = none
}
}
} $else $if field.typ is u8 {
typ.$(field.name) = res[json_name]!.u64()
Expand Down

0 comments on commit d585e50

Please sign in to comment.