Skip to content

Commit 2df23a6

Browse files
authored
json: fix ptr field access (#17690)
1 parent aee76c5 commit 2df23a6

File tree

2 files changed

+51
-5
lines changed

2 files changed

+51
-5
lines changed

vlib/json/json_encode_with_mut_test.v

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
module main
2+
3+
import json
4+
5+
pub enum PlatformType {
6+
unknown
7+
osx
8+
ubuntu
9+
alpine
10+
}
11+
12+
pub enum CPUType {
13+
unknown
14+
intel
15+
arm
16+
intel32
17+
arm32
18+
}
19+
20+
[heap]
21+
pub struct Node {
22+
pub:
23+
name string = 'mymachine'
24+
pub mut:
25+
platform PlatformType
26+
cputype CPUType
27+
done map[string]string
28+
environment map[string]string
29+
}
30+
31+
pub fn (mut node Node) save() ! {
32+
data := json.encode(node)
33+
dump(data)
34+
}
35+
36+
fn test_encode_with_mut_struct() {
37+
mut n := Node{
38+
platform: .osx
39+
cputype: .unknown
40+
}
41+
n.save() or { panic(err) }
42+
}

vlib/v/gen/c/json.v

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -520,21 +520,25 @@ fn (mut g Gen) gen_struct_enc_dec(utyp ast.Type, type_info ast.TypeInfo, styp st
520520
}
521521
}
522522
if field_sym.kind == .enum_ {
523-
enc.writeln('\tcJSON_AddItemToObject(o, "${name}", json__encode_u64(${prefix_enc}.${c_name(field.name)}));\n')
523+
enc.writeln('\tcJSON_AddItemToObject(o, "${name}", json__encode_u64(${prefix_enc}${op}${c_name(field.name)}));\n')
524524
} else {
525525
if field_sym.name == 'time.Time' {
526526
// time struct requires special treatment
527527
// it has to be encoded as a unix timestamp number
528-
enc.writeln('\tcJSON_AddItemToObject(o, "${name}", json__encode_u64(${prefix_enc}.${c_name(field.name)}._v_unix));')
528+
enc.writeln('\tcJSON_AddItemToObject(o, "${name}", json__encode_u64(${prefix_enc}${op}${c_name(field.name)}._v_unix));')
529529
} else {
530530
if !field.typ.is_real_pointer() {
531531
enc.writeln('\tcJSON_AddItemToObject(o, "${name}", ${enc_name}(${prefix_enc}${op}${c_name(field.name)})); /*A*/')
532532
} else {
533533
arg_prefix := if field.typ.is_ptr() { '' } else { '*' }
534534
sptr_value := '${prefix_enc}${op}${c_name(field.name)}'
535-
enc.writeln('\tif (${sptr_value} != 0) {')
536-
enc.writeln('\t\tcJSON_AddItemToObject(o, "${name}", ${enc_name}(${arg_prefix}${sptr_value}));')
537-
enc.writeln('\t}\n')
535+
if !field.typ.has_flag(.option) {
536+
enc.writeln('\tif (${sptr_value} != 0) {')
537+
enc.writeln('\t\tcJSON_AddItemToObject(o, "${name}", ${enc_name}(${arg_prefix}${sptr_value}));')
538+
enc.writeln('\t}\n')
539+
} else {
540+
enc.writeln('\t\tcJSON_AddItemToObject(o, "${name}", ${enc_name}(${arg_prefix}${sptr_value}));')
541+
}
538542
}
539543
}
540544
}

0 commit comments

Comments
 (0)