toon_format/encode/
primitives.rs

1pub fn is_primitive(value: &serde_json::Value) -> bool {
2    matches!(
3        value,
4        serde_json::Value::Null
5            | serde_json::Value::Bool(_)
6            | serde_json::Value::Number(_)
7            | serde_json::Value::String(_)
8    )
9}
10
11pub fn all_primitives(values: &[serde_json::Value]) -> bool {
12    values.iter().all(is_primitive)
13}
14
15/// Recursively normalize JSON values.
16pub fn normalize_value(value: serde_json::Value) -> serde_json::Value {
17    match value {
18        serde_json::Value::Null => serde_json::Value::Null,
19        serde_json::Value::Bool(b) => serde_json::Value::Bool(b),
20        serde_json::Value::Number(n) => serde_json::Value::Number(n),
21        serde_json::Value::String(s) => serde_json::Value::String(s),
22        serde_json::Value::Array(arr) => {
23            serde_json::Value::Array(arr.into_iter().map(normalize_value).collect())
24        }
25        serde_json::Value::Object(obj) => serde_json::Value::Object(
26            obj.into_iter()
27                .map(|(k, v)| (k, normalize_value(v)))
28                .collect(),
29        ),
30    }
31}
32
33#[cfg(test)]
34mod tests {
35    use serde_json::json;
36
37    use super::*;
38
39    #[test]
40    fn test_is_primitive() {
41        assert!(is_primitive(&json!(null)));
42        assert!(is_primitive(&json!(true)));
43        assert!(is_primitive(&json!(42)));
44        assert!(is_primitive(&json!("hello")));
45        assert!(!is_primitive(&json!([])));
46        assert!(!is_primitive(&json!({})));
47    }
48
49    #[test]
50    fn test_all_primitives() {
51        assert!(all_primitives(&[json!(1), json!(2), json!(3)]));
52        assert!(all_primitives(&[json!("a"), json!("b")]));
53        assert!(all_primitives(&[json!(null), json!(true), json!(42)]));
54        assert!(!all_primitives(&[json!(1), json!([]), json!(3)]));
55        assert!(!all_primitives(&[json!({})]));
56    }
57
58    #[test]
59    fn test_normalize_value() {
60        assert_eq!(normalize_value(json!(null)), json!(null));
61        assert_eq!(normalize_value(json!(42)), json!(42));
62        assert_eq!(normalize_value(json!("hello")), json!("hello"));
63
64        let normalized = normalize_value(json!({"a": 1, "b": [2, 3]}));
65        assert_eq!(normalized, json!({"a": 1, "b": [2, 3]}));
66    }
67}