firebase_rs_sdk/util/
obj.rs

1use serde_json::{Map, Value};
2
3pub fn is_empty(value: &Value) -> bool {
4    match value {
5        Value::Object(map) => map.is_empty(),
6        Value::Array(array) => array.is_empty(),
7        Value::Null => true,
8        _ => false,
9    }
10}
11
12pub fn deep_equal(a: &Value, b: &Value) -> bool {
13    a == b
14}
15
16pub fn map_values<F>(input: &Map<String, Value>, mut f: F) -> Map<String, Value>
17where
18    F: FnMut(&Value, &str, &Map<String, Value>) -> Value,
19{
20    let mut result = Map::new();
21    for (key, value) in input.iter() {
22        result.insert(key.clone(), f(value, key, input));
23    }
24    result
25}
26
27#[cfg(test)]
28mod tests {
29    use super::*;
30    use serde_json::json;
31
32    #[test]
33    fn empty_checks() {
34        assert!(is_empty(&json!({})));
35        assert!(is_empty(&json!([])));
36        assert!(!is_empty(&json!({"a": 1})));
37    }
38
39    #[test]
40    fn deep_equal_uses_value_eq() {
41        assert!(deep_equal(&json!({"a": 1}), &json!({"a": 1})));
42        assert!(!deep_equal(&json!({"a": 1}), &json!({"a": 2})));
43    }
44
45    #[test]
46    fn map_values_transforms_entries() {
47        let input = json!({"a": 1, "b": 2}).as_object().unwrap().clone();
48        let mapped = map_values(&input, |value, _key, _| match value {
49            Value::Number(num) => {
50                Value::Number(serde_json::Number::from(num.as_i64().unwrap() * 2))
51            }
52            other => other.clone(),
53        });
54        assert_eq!(mapped.get("a").unwrap(), &json!(2));
55        assert_eq!(mapped.get("b").unwrap(), &json!(4));
56    }
57}