From e2853112901e0565dc262f83be6341a6cb609ce4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Aur=C3=A9lien=20Foucault?= Date: Mon, 24 Jun 2019 22:25:35 +0200 Subject: [PATCH] Add all types of int and float to json decode/encode --- compiler/jsgen.v | 4 ++- json/json_primitives.v | 81 ++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 84 insertions(+), 1 deletion(-) diff --git a/compiler/jsgen.v b/compiler/jsgen.v index 8dd0dd5a5b..6993fc5c93 100644 --- a/compiler/jsgen.v +++ b/compiler/jsgen.v @@ -109,7 +109,9 @@ string res = tos2(""); } 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 { diff --git a/json/json_primitives.v b/json/json_primitives.v index 1d580ce391..1f5f8aca45 100644 --- a/json/json_primitives.v +++ b/json/json_primitives.v @@ -12,6 +12,7 @@ module json #include "cJSON.h" struct C.cJSON { valueint int + valuedouble float valuestring byteptr } @@ -22,6 +23,58 @@ fn jsdecode_int(root *C.cJSON) int { 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 { if isnil(root) { 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 { 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 { return C.cJSON_CreateBool(val) }