k8_diff/json/
mod.rs

1mod diff;
2mod se;
3
4use serde_json::Map;
5use serde_json::Value;
6use std::collections::HashMap;
7
8use crate::Changes;
9use crate::Diff;
10use crate::DiffError;
11
12type SerdeObj = Map<String, Value>;
13pub type JsonDiff = Diff<Value, PatchObject>;
14
15#[derive(Debug)]
16pub struct PatchObject(HashMap<String, JsonDiff>);
17
18impl PatchObject {
19    // diff { "a": 1,"b": 2}, { "a": 3, "b": 2} => { "a": 1}
20    fn diff(old: &SerdeObj, new: &SerdeObj) -> Result<Self, DiffError> {
21        let mut map: HashMap<String, JsonDiff> = HashMap::new();
22
23        for (key, new_val) in new.iter() {
24            match old.get(key) {
25                Some(old_val) => {
26                    if old_val != new_val {
27                        let diff_value = old_val.diff(new_val)?;
28                        map.insert(key.clone(), diff_value);
29                    }
30                }
31                _ => {
32                    map.insert(key.clone(), Diff::Replace(new_val.clone())); // just replace with new if key doesn't match
33                }
34            }
35        }
36
37        Ok(PatchObject(map))
38    }
39
40    fn get_inner_ref(&self) -> &HashMap<String, JsonDiff> {
41        &self.0
42    }
43}