Skip to main content

inochi2d_parser/
json_extra.rs

1use json::{JsonValue, object::Object};
2
3pub(crate) trait JsonExt {
4    fn get(&self, key: &str) -> Option<&JsonValue>;
5    fn get_str(&self, key: &str) -> Option<&str>;
6    fn get_f32(&self, key: &str, default: f32) -> f32;
7    fn get_bool(&self, key: &str, default: bool) -> bool;
8    fn get_as_bool(&self, key: &str) -> Option<bool>;
9    fn get_u32(&self, key: &str) -> Option<u32>;
10    fn get_array(&self, key: &str) -> Option<&[JsonValue]>;
11    fn get_vec2(&self, key: &str) -> Option<[f32; 2]>;
12    fn get_vec3(&self, key: &str) -> Option<[f32; 3]>;
13    fn as_array(&self) -> Option<&[JsonValue]>;
14    fn as_object(&self) -> Option<&Object>;
15}
16
17impl JsonExt for JsonValue {
18    #[inline]
19    fn get(&self, key: &str) -> Option<&JsonValue> {
20        match self {
21            JsonValue::Object(obj) => obj.get(key),
22            _ => None,
23        }
24    }
25
26    #[inline]
27    fn get_str(&self, key: &str) -> Option<&str> {
28        self.get(key)?.as_str()
29    }
30
31    #[inline]
32    fn get_f32(&self, key: &str, default: f32) -> f32 {
33        self.get(key)
34            .and_then(|v| v.as_f32())
35            .unwrap_or(default)
36    }
37
38    #[inline]
39    fn get_bool(&self, key: &str, default: bool) -> bool {
40        self.get(key)
41            .and_then(|v| v.as_bool())
42            .unwrap_or(default)
43    }
44
45    #[inline]
46    fn get_as_bool(&self, key: &str) -> Option<bool> {
47        self.get(key)?.as_bool()
48    }
49
50    #[inline]
51    fn get_u32(&self, key: &str) -> Option<u32> {
52        self.get(key)?.as_u32()
53    }
54
55    #[inline]
56    fn get_array(&self, key: &str) -> Option<&[JsonValue]> {
57        match self.get(key)? {
58            JsonValue::Array(arr) => Some(arr),
59            _ => None,
60        }
61    }
62
63    #[inline]
64    fn get_vec2(&self, key: &str) -> Option<[f32; 2]> {
65        let arr = self.get_array(key)?;
66        if arr.len() != 2 {
67            return None;
68        }
69        let x = arr[0].as_f64().unwrap_or(0.0) as f32;
70        let y = arr[1].as_f64().unwrap_or(0.0) as f32;
71        Some([x, y])
72    }
73
74    #[inline]
75    fn get_vec3(&self, key: &str) -> Option<[f32; 3]> {
76        let arr = self.get_array(key)?;
77        if arr.len() != 3 {
78            return None;
79        }
80        let x = arr[0].as_f64().unwrap_or(0.0) as f32;
81        let y = arr[1].as_f64().unwrap_or(0.0) as f32;
82        let z = arr[2].as_f64().unwrap_or(0.0) as f32;
83        Some([x, y, z])
84    }
85
86    #[inline]
87    fn as_array(&self) -> Option<&[JsonValue]> {
88        match self {
89            JsonValue::Array(arr) => Some(arr),
90            _ => None,
91        }
92    }
93
94    #[inline]
95    fn as_object(&self) -> Option<&Object> {
96        match self {
97            JsonValue::Object(obj) => Some(obj),
98            _ => None,
99        }
100    }
101}