json: allow i32 decoding and encoding (#21162)

This commit is contained in:
Swastik Baranwal 2024-04-02 07:54:36 +05:30 committed by GitHub
parent c086bee5be
commit 656009dc62
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
2 changed files with 26 additions and 4 deletions

16
vlib/json/json_i32_test.v Normal file
View file

@ -0,0 +1,16 @@
import json
pub struct StructB {
kind string
value i32
}
fn test_json_i32() {
struct_b := json.decode(StructB, '{"kind": "Int32", "value": 100}')!
assert struct_b == StructB{
kind: 'Int32'
value: 100
}
assert json.encode(struct_b) == '{"kind":"Int32","value":100}'
}

View file

@ -902,20 +902,26 @@ fn gen_js_get_opt(dec_name string, field_type string, styp string, tmp string, n
} }
fn js_enc_name(typ string) string { fn js_enc_name(typ string) string {
suffix := typ.replace('*', '_ptr') mut suffix := typ.replace('*', '_ptr')
if typ == 'i32' {
suffix = typ.replace('i32', 'int')
}
name := 'json__encode_${suffix}' name := 'json__encode_${suffix}'
return util.no_dots(name) return util.no_dots(name)
} }
fn js_dec_name(typ string) string { fn js_dec_name(typ string) string {
suffix := typ.replace('*', '_ptr') mut suffix := typ.replace('*', '_ptr')
if typ == 'i32' {
suffix = typ.replace('i32', 'int')
}
name := 'json__decode_${suffix}' name := 'json__decode_${suffix}'
return util.no_dots(name) return util.no_dots(name)
} }
fn is_js_prim(typ string) bool { fn is_js_prim(typ string) bool {
return typ in ['int', 'rune', 'string', 'bool', 'f32', 'f64', 'i8', 'i16', 'i64', 'u8', 'u16', return typ in ['int', 'rune', 'string', 'bool', 'f32', 'f64', 'i8', 'i16', 'i32', 'i64', 'u8',
'u32', 'u64', 'byte'] 'u16', 'u32', 'u64', 'byte']
} }
fn (mut g Gen) decode_array(utyp ast.Type, value_type ast.Type, fixed_array_size int, ret_styp string) string { fn (mut g Gen) decode_array(utyp ast.Type, value_type ast.Type, fixed_array_size int, ret_styp string) string {