1
0
mirror of https://github.com/vlang/v.git synced 2023-08-10 21:13:21 +03:00

x.json2: add support for i8, i16, u8, u16, u32 (fix #16484)

This commit is contained in:
Delyan Angelov
2022-11-19 11:52:17 +02:00
parent 79b4cfb42a
commit 6b0743bb07
6 changed files with 152 additions and 86 deletions

View File

@ -5,18 +5,6 @@ module json2
import strings
pub const (
null = Null{}
)
pub interface Decodable {
from_json(f Any)
}
pub interface Encodable {
json_str() string
}
// Decodes a JSON string into an `Any` type. Returns an option.
pub fn raw_decode(src string) !Any {
mut p := new_parser(src, true)
@ -45,32 +33,16 @@ pub fn encode<T>(val T) string {
}
default_encoder.encode_value(val, mut sb) or {
dump(err)
default_encoder.encode_value<Null>(json2.null, mut sb) or {}
default_encoder.encode_value<Null>(null, mut sb) or {}
}
return sb.str()
}
// as_map uses `Any` as a map.
pub fn (f Any) as_map() map[string]Any {
if f is map[string]Any {
return f
} else if f is []Any {
mut mp := map[string]Any{}
for i, fi in f {
mp['${i}'] = fi
}
return mp
}
return {
'0': f
}
}
// int uses `Any` as an integer.
pub fn (f Any) int() int {
match f {
int { return f }
i64, f32, f64, bool { return int(f) }
i8, i16, i64, u8, u16, u32, u64, f32, f64, bool { return int(f) }
else { return 0 }
}
}
@ -79,7 +51,7 @@ pub fn (f Any) int() int {
pub fn (f Any) i64() i64 {
match f {
i64 { return f }
int, f32, f64, bool { return i64(f) }
i8, i16, int, u8, u16, u32, u64, f32, f64, bool { return i64(f) }
else { return 0 }
}
}
@ -88,7 +60,7 @@ pub fn (f Any) i64() i64 {
pub fn (f Any) u64() u64 {
match f {
u64 { return f }
int, i64, f32, f64, bool { return u64(f) }
u8, u16, u32, i8, i16, int, i64, f32, f64, bool { return u64(f) }
else { return 0 }
}
}
@ -97,20 +69,32 @@ pub fn (f Any) u64() u64 {
pub fn (f Any) f32() f32 {
match f {
f32 { return f }
int, i64, f64 { return f32(f) }
bool, i8, i16, int, i64, u8, u16, u32, u64, f64 { return f32(f) }
else { return 0.0 }
}
}
// f64 uses `Any` as a float.
// f64 uses `Any` as a 64-bit float.
pub fn (f Any) f64() f64 {
match f {
f64 { return f }
int, i64, f32 { return f64(f) }
i8, i16, int, i64, u8, u16, u32, u64, f32 { return f64(f) }
else { return 0.0 }
}
}
// bool uses `Any` as a bool.
pub fn (f Any) bool() bool {
match f {
bool { return f }
string { return f.bool() }
i8, i16, int, i64 { return i64(f) != 0 }
u8, u16, u32, u64 { return u64(f) != 0 }
f32, f64 { return f64(f) != 0.0 }
else { return false }
}
}
// arr uses `Any` as an array.
pub fn (f Any) arr() []Any {
if f is []Any {
@ -125,11 +109,18 @@ pub fn (f Any) arr() []Any {
return [f]
}
// bool uses `Any` as a bool
pub fn (f Any) bool() bool {
match f {
bool { return f }
string { return f.bool() }
else { return false }
// as_map uses `Any` as a map.
pub fn (f Any) as_map() map[string]Any {
if f is map[string]Any {
return f
} else if f is []Any {
mut mp := map[string]Any{}
for i, fi in f {
mp['${i}'] = fi
}
return mp
}
return {
'0': f
}
}