1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
pub mod union;

use crate::index::{Index, Path as IndexPath};
use crate::iter::Traverser;
use serde_json::Value;
pub use union::Union;

pub trait Merge: Sized {
    fn merge<T>(&mut self, other: &Self)
    where
        T: Traverser;

    fn merge_recursive<T>(&mut self, other: &Self)
    where
        T: Traverser;

    fn merge_by<T, F>(&mut self, other: &Self, merge: &mut F)
    where
        T: Traverser,
        F: FnMut(&IndexPath, &mut Value, Option<&Value>) -> bool;

    fn merge_by_recursive<T, F>(&mut self, other: &Self, merge: &mut F)
    where
        T: Traverser,
        F: FnMut(&IndexPath, &mut Value, Option<&Value>) -> bool;

    #[inline]
    #[must_use]
    fn merged<T>(mut self, other: &Self) -> Self
    where
        T: Traverser,
    {
        self.merge::<T>(other);
        self
    }

    #[inline]
    #[must_use]
    fn merged_recursive<T>(mut self, other: &Self) -> Self
    where
        T: Traverser,
    {
        self.merge_recursive::<T>(other);
        self
    }

    #[inline]
    #[must_use]
    fn merged_by<T, F>(mut self, other: &Self, merge: &mut F) -> Self
    where
        T: Traverser,
        F: FnMut(&IndexPath, &mut Value, Option<&Value>) -> bool,
    {
        self.merge_by::<T, F>(other, merge);
        self
    }

    #[inline]
    #[must_use]
    fn merged_by_recursive<T, F>(mut self, other: &Self, merge: &mut F) -> Self
    where
        T: Traverser,
        F: FnMut(&IndexPath, &mut Value, Option<&Value>) -> bool,
    {
        self.merge_by_recursive::<T, F>(other, merge);
        self
    }
}

impl Merge for Value {
    #[inline]
    fn merge<T>(&mut self, other: &Self)
    where
        T: Traverser,
    {
        self.merge_by::<T, _>(other, &mut merge_func);
    }

    #[inline]
    fn merge_recursive<T>(&mut self, other: &Self)
    where
        T: Traverser,
    {
        self.merge_by_recursive::<T, _>(other, &mut merge_func);
    }

    #[inline]
    fn merge_by<T, F>(&mut self, other: &Self, merge: &mut F)
    where
        T: Traverser,
        F: FnMut(&IndexPath, &mut Value, Option<&Value>) -> bool,
    {
        let mut traverser = T::new();
        traverser.set_limit(None);
        traverser.set_depth(1);
        while traverser
            .process_next(other, |idx, new_value| {
                if let Some(value) = self.get_index_mut(idx) {
                    merge(idx, value, new_value)
                } else {
                    true
                }
            })
            .is_some()
        {}
    }

    #[inline]
    fn merge_by_recursive<T, F>(&mut self, other: &Self, merge: &mut F)
    where
        T: Traverser,
        F: FnMut(&IndexPath, &mut Value, Option<&Value>) -> bool,
    {
        let mut traverser = T::new();
        traverser.set_limit(None);
        traverser.set_depth(None);
        while traverser
            .process_next(other, |idx, new_value| {
                if let Some(value) = self.get_index_mut(idx) {
                    merge(idx, value, new_value)
                } else {
                    true
                }
            })
            .is_some()
        {}
    }
}

fn merge_func(_idx: &IndexPath, this: &mut Value, other: Option<&Value>) -> bool {
    match (this, other) {
        // add new fields when merging two objects
        (&mut Value::Object(ref mut this), Some(&Value::Object(ref other))) => {
            for k in other.keys() {
                this.entry(k.clone()).or_insert(Value::Null);
            }
            true
        }
        // extend array with other array
        (&mut Value::Array(ref mut this), Some(&Value::Array(ref other))) => {
            this.extend(other.clone());
            false
        }
        // extend array with other value
        (&mut Value::Array(ref mut this), Some(other)) => {
            this.extend([other.clone()]);
            false
        }
        // do not overwrite anything with null
        (_, Some(&Value::Null)) => false,
        // overwrite this with other
        (this, Some(other)) => {
            *this = other.clone();
            false
        }
        _ => false,
    }
}

#[cfg(test)]
pub mod test {
    use super::Merge;
    use crate::iter::dfs::Dfs;
    use pretty_assertions::assert_eq;
    use serde_json::json;

    #[test]
    fn merge_array_string() {
        let base = json!(["a", "b"]);
        let merge = json!(["b", "c"]);
        assert_eq!(
            &base.merged_recursive::<Dfs>(&merge),
            &json!(["a", "b", "b", "c"])
        );
    }

    #[test]
    fn merge_array_object() {
        let base = json!([{"value": "a"}, {"value": "b"}]);
        let merge = json!([{"value": "b"}, {"value": "c"}]);
        dbg!(base.clone().merged_recursive::<Dfs>(&merge));
        assert_eq!(
            &base.merged_recursive::<Dfs>(&merge),
            &json!([
                {"value": "a"},
                {"value": "b"},
                {"value": "b"},
                {"value": "c"}
            ])
        );
    }

    #[test]
    fn merge_object() {
        let base = json!({"value1": "a", "value2": "b"});
        let merge = json!({"value1": "a", "value2": "c", "value3": "d"});
        assert_eq!(
            &base.merged_recursive::<Dfs>(&merge),
            &json!({
                "value1": "a",
                "value2": "c",
                "value3": "d",
            })
        );
    }

    #[test]
    fn merge_string() {
        let base = json!("a");
        let merge = json!("b");
        assert_eq!(&base.merged_recursive::<Dfs>(&merge), &merge);
    }
}