Add all types of int and float to json decode/encode

pull/544/head
Aurélien Foucault 2019-06-24 22:25:35 +02:00 committed by Alex Medvednikov
parent 877f9e7070
commit e285311290
2 changed files with 84 additions and 1 deletions

View File

@ -109,7 +109,9 @@ string res = tos2("");
} }
fn is_js_prim(typ string) bool { fn is_js_prim(typ string) bool {
return typ == 'int' || typ == 'string' || typ == 'bool' return typ == 'int' || typ == 'string' ||
typ == 'bool' || typ == 'float' || typ == 'f32' || typ == 'f64' ||
typ == 'i8' || typ == 'i16' || typ == 'i32' || typ == 'i64'
} }
fn (p mut Parser) decode_array(typ string) string { fn (p mut Parser) decode_array(typ string) string {

View File

@ -12,6 +12,7 @@ module json
#include "cJSON.h" #include "cJSON.h"
struct C.cJSON { struct C.cJSON {
valueint int valueint int
valuedouble float
valuestring byteptr valuestring byteptr
} }
@ -22,6 +23,58 @@ fn jsdecode_int(root *C.cJSON) int {
return root.valueint return root.valueint
} }
//TODO: Refactor with generics when it will be avaible
fn jsdecode_i8(root *C.cJSON) i8 {
if isnil(root) {
return i8(0)
}
return i8(root.valueint)
}
fn jsdecode_i16(root *C.cJSON) i16 {
if isnil(root) {
return i16(0)
}
return i16(root.valueint)
}
fn jsdecode_i32(root *C.cJSON) i32 {
if isnil(root) {
return i32(0)
}
return i32(root.valueint)
}
fn jsdecode_i64(root *C.cJSON) i64 {
if isnil(root) {
return i64(0)
}
return i64(root.valuedouble) //i64 is double in C
}
fn jsdecode_float(root *C.cJSON) float {
if isnil(root) {
return 0
}
return root.valuedouble
}
fn jsdecode_f32(root *C.cJSON) f32 {
if isnil(root) {
return f32(0)
}
return f32(root.valuedouble)
}
fn jsdecode_f64(root *C.cJSON) f64 {
if isnil(root) {
return f64(0)
}
return f64(root.valuedouble)
}
fn jsdecode_string(root *C.cJSON) string { fn jsdecode_string(root *C.cJSON) string {
if isnil(root) { if isnil(root) {
return '' return ''
@ -42,10 +95,38 @@ fn jsdecode_bool(root *C.cJSON) bool {
} }
// /////////////////// // ///////////////////
//TODO: Refactor with Generics when it will be available
fn jsencode_int(val int) *C.cJSON { fn jsencode_int(val int) *C.cJSON {
return C.cJSON_CreateNumber(val) return C.cJSON_CreateNumber(val)
} }
fn jsencode_i8(val i8) *C.cJSON {
return C.cJSON_CreateNumber(val)
}
fn jsencode_i16(val i16) *C.cJSON {
return C.cJSON_CreateNumber(val)
}
fn jsencode_i32(val i32) *C.cJSON {
return C.cJSON_CreateNumber(val)
}
fn jsencode_i64(val i64) *C.cJSON {
return C.cJSON_CreateNumber(val)
}
fn jsencode_float(val float) *C.cJSON {
return C.cJSON_CreateNumber(val)
}
fn jsencode_f32(val f32) *C.cJSON {
return C.cJSON_CreateNumber(val)
}
fn jsencode_f64(val f64) *C.cJSON {
return C.cJSON_CreateNumber(val)
}
fn jsencode_bool(val bool) *C.cJSON { fn jsencode_bool(val bool) *C.cJSON {
return C.cJSON_CreateBool(val) return C.cJSON_CreateBool(val)
} }