json: fix encode/decode of fixed arrays (fix #22369) (#22448)

This commit is contained in:
Felipe Pena 2024-10-08 13:31:34 -03:00 committed by GitHub
parent e14bc6077b
commit ef72f97b96
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
2 changed files with 40 additions and 1 deletions

View file

@ -0,0 +1,25 @@
import json
struct Base {
options Options
profiles Profiles
}
struct Options {
cfg [6]u8
}
struct Profiles {
cfg [4][7]u8
}
fn test_main() {
a := json.encode(Base{})
println(a)
assert a.contains('"cfg":[[0,0,0,0,0,0,0],[0,0,0,0,0,0,0],[0,0,0,0,0,0,0],[0,0,0,0,0,0,0]]')
b := json.decode(Base, a)!
assert b.options.cfg.len == 6
assert b.profiles.cfg.len == 4
assert b.profiles.cfg[0].len == 7
}

View file

@ -983,6 +983,7 @@ fn (mut g Gen) decode_array(utyp ast.Type, value_type ast.Type, fixed_array_size
mut fixed_array_idx := ''
mut fixed_array_idx_increment := ''
mut array_element_assign := ''
is_array_fixed_val := g.table.final_sym(value_type).kind == .array_fixed
if utyp.has_flag(.option) {
if fixed_array_size > -1 {
fixed_array_idx += 'int fixed_array_idx = 0;'
@ -994,7 +995,11 @@ fn (mut g Gen) decode_array(utyp ast.Type, value_type ast.Type, fixed_array_size
array_free_str += 'array_free(&res.data);'
}
} else {
if fixed_array_size > -1 {
if is_array_fixed_val {
fixed_array_idx += 'int fixed_array_idx = 0;'
array_element_assign += 'memcpy(res[fixed_array_idx], val, sizeof(${styp}));'
fixed_array_idx_increment += 'fixed_array_idx++;'
} else if fixed_array_size > -1 {
fixed_array_idx += 'int fixed_array_idx = 0;'
array_element_assign += 'res[fixed_array_idx] = val;'
fixed_array_idx_increment += 'fixed_array_idx++;'
@ -1008,6 +1013,15 @@ fn (mut g Gen) decode_array(utyp ast.Type, value_type ast.Type, fixed_array_size
mut s := ''
if is_js_prim(styp) {
s = '${styp} val = ${fn_name}((cJSON *)jsval); '
} else if is_array_fixed_val {
s = '
${result_name}_${styp} val2 = ${fn_name} ((cJSON *)jsval);
if(val2.is_error) {
${array_free_str}
return *(${result_name}_${ret_styp}*)&val2;
}
${styp} val;
memcpy(&val, (${styp}*)val2.data, sizeof(${styp}));'
} else {
s = '
${result_name}_${styp} val2 = ${fn_name} ((cJSON *)jsval);