Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

json: fix array fixed encode/decode #22448

Merged
merged 1 commit into from
Oct 8, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 25 additions & 0 deletions vlib/json/json_fixed_array_test.v
Original file line number Diff line number Diff line change
@@ -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
}
16 changes: 15 additions & 1 deletion vlib/v/gen/c/json.v
Original file line number Diff line number Diff line change
Expand Up @@ -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;'
Expand All @@ -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++;'
Expand All @@ -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);
Expand Down
Loading