cgen: fix ptr field encoding for json (fix #22717) (#22720)

This commit is contained in:
Felipe Pena 2024-11-01 02:28:37 -03:00 committed by GitHub
parent ee4f29fd87
commit a9e814ff68
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
2 changed files with 33 additions and 1 deletions

View file

@ -0,0 +1,31 @@
import json
struct Number {
min int
max int
}
pub struct Resp {
pub:
options []string @[omitempty]
number &Number = unsafe { nil } @[omitempty]
}
fn (r Resp) str() string {
return json.encode(r)
}
fn test_main() {
r1 := Resp{
options: ['first', 'second']
}
r2 := Resp{
number: &Number{0, 0}
}
r3 := Resp{
number: &Number{1, 2}
}
assert r1.str() == '{"options":["first","second"]}'
assert r2.str() == '{"number":{"min":0,"max":0}}'
assert r3.str() == '{"number":{"min":1,"max":2}}'
}

View file

@ -842,7 +842,8 @@ fn (mut g Gen) gen_struct_enc_dec(utyp ast.Type, type_info ast.TypeInfo, styp st
} else if field.typ == ast.string_type {
enc.writeln('${indent}if (${prefix_enc}${op}${c_name(field.name)}.len != 0)')
} else {
if field_sym.kind in [.alias, .sum_type, .map, .array, .struct] {
if !field.typ.is_ptr()
&& field_sym.kind in [.alias, .sum_type, .map, .array, .struct] {
ptr_typ := g.equality_fn(field.typ)
if field_sym.kind == .alias {
enc.writeln('${indent}if (!${ptr_typ}_alias_eq(${prefix_enc}${op}${c_name(field.name)}, ${g.type_default(field.typ)}))')