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
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
use diffs::{myers, Diff, Replace};
use std::collections::HashMap;
use std::collections::HashSet;

use crate::enums::Error;
use serde_json::Map;
use serde_json::Value;

use crate::ds::key_node::KeyNode;
use crate::ds::mismatch::Mismatch;

pub fn compare_jsons(a: &str, b: &str) -> Result<Mismatch, Error> {
    let value1 = serde_json::from_str(a)?;
    let value2 = serde_json::from_str(b)?;
    Ok(match_json(&value1, &value2))
}
fn values_to_node(vec: Vec<(usize, &Value)>) -> KeyNode {
    if vec.is_empty() {
        KeyNode::Nil
    } else {
        KeyNode::Node(
            vec.into_iter()
                .map(|(id, val)| (format!("[l: {id}] - {}", val.to_string()), KeyNode::Nil))
                .collect(),
        )
    }
}

struct ListDiffHandler<'a> {
    replaced: &'a mut Vec<(usize, usize, usize, usize)>,
    deletion: &'a mut Vec<(usize, usize)>,
    insertion: &'a mut Vec<(usize, usize)>,
}
impl<'a> ListDiffHandler<'a> {
    pub fn new(
        replaced: &'a mut Vec<(usize, usize, usize, usize)>,
        deletion: &'a mut Vec<(usize, usize)>,
        insertion: &'a mut Vec<(usize, usize)>,
    ) -> Self {
        Self {
            replaced,
            deletion,
            insertion,
        }
    }
}
impl<'a> Diff for ListDiffHandler<'a> {
    type Error = ();
    fn delete(&mut self, old: usize, len: usize, _new: usize) -> Result<(), ()> {
        self.deletion.push((old, len));
        Ok(())
    }
    fn insert(&mut self, _o: usize, new: usize, len: usize) -> Result<(), ()> {
        self.insertion.push((new, len));
        Ok(())
    }
    fn replace(&mut self, old: usize, len: usize, new: usize, new_len: usize) -> Result<(), ()> {
        self.replaced.push((old, len, new, new_len));
        Ok(())
    }
}

pub fn match_json(value1: &Value, value2: &Value) -> Mismatch {
    match (value1, value2) {
        (Value::Object(a), Value::Object(b)) => {
            let diff = intersect_maps(a, b);
            let mut left_only_keys = get_map_of_keys(diff.left_only);
            let mut right_only_keys = get_map_of_keys(diff.right_only);
            let intersection_keys = diff.intersection;

            let mut unequal_keys = KeyNode::Nil;

            if let Some(intersection_keys) = intersection_keys {
                for key in intersection_keys {
                    let Mismatch {
                        left_only_keys: l,
                        right_only_keys: r,
                        keys_in_both: u,
                    } = match_json(a.get(&key).unwrap(), b.get(&key).unwrap());
                    left_only_keys = insert_child_key_map(left_only_keys, l, &key);
                    right_only_keys = insert_child_key_map(right_only_keys, r, &key);
                    unequal_keys = insert_child_key_map(unequal_keys, u, &key);
                }
            }
            Mismatch::new(left_only_keys, right_only_keys, unequal_keys)
        }
        // this clearly needs to be improved! myers algorithm or whatever?
        (Value::Array(a), Value::Array(b)) => {
            let mut replaced = Vec::new();
            let mut deleted = Vec::new();
            let mut inserted = Vec::new();

            let mut diff = Replace::new(ListDiffHandler::new(
                &mut replaced,
                &mut deleted,
                &mut inserted,
            ));
            myers::diff(&mut diff, a, 0, a.len(), b, 0, b.len()).unwrap();

            let mismatch: Vec<_> = replaced
                .into_iter()
                .flat_map(|(o, ol, n, _nl)| {
                    (0..ol).map(move |i| (o + i, match_json(&a[o + i], &b[n + i]).keys_in_both))
                })
                .collect();

            let left_only_values: Vec<_> = deleted
                .into_iter()
                .flat_map(|(o, ol)| (o..o + ol).map(|i| (i, &a[i])))
                .collect();

            let right_only_values: Vec<_> = inserted
                .into_iter()
                .flat_map(|(n, nl)| (n..n + nl).map(|i| (i, &b[i])))
                .collect();

            let left_only_nodes = values_to_node(left_only_values);
            let right_only_nodes = values_to_node(right_only_values);
            let mismatch = if mismatch.is_empty() {
                KeyNode::Nil
            } else {
                KeyNode::Array(mismatch)
            };
            Mismatch::new(left_only_nodes, right_only_nodes, mismatch)
        }
        (a, b) => {
            if a == b {
                Mismatch::new(KeyNode::Nil, KeyNode::Nil, KeyNode::Nil)
            } else {
                Mismatch::new(
                    KeyNode::Nil,
                    KeyNode::Nil,
                    KeyNode::Value(a.clone(), b.clone()),
                )
            }
        }
    }
}

fn get_map_of_keys(set: Option<HashSet<String>>) -> KeyNode {
    if let Some(set) = set {
        KeyNode::Node(
            set.iter()
                .map(|key| (String::from(key), KeyNode::Nil))
                .collect(),
        )
    } else {
        KeyNode::Nil
    }
}

fn insert_child_key_map(parent: KeyNode, child: KeyNode, key: &String) -> KeyNode {
    if child == KeyNode::Nil {
        return parent;
    }
    if let KeyNode::Node(mut map) = parent {
        map.insert(String::from(key), child);
        KeyNode::Node(map) // This is weird! I just wanted to return back `parent` here
    } else if let KeyNode::Nil = parent {
        let mut map = HashMap::new();
        map.insert(String::from(key), child);
        KeyNode::Node(map)
    } else {
        parent // TODO Trying to insert child node in a Value variant : Should not happen => Throw an error instead.
    }
}

struct MapDifference {
    left_only: Option<HashSet<String>>,
    right_only: Option<HashSet<String>>,
    intersection: Option<HashSet<String>>,
}

impl MapDifference {
    pub fn new(
        left_only: Option<HashSet<String>>,
        right_only: Option<HashSet<String>>,
        intersection: Option<HashSet<String>>,
    ) -> Self {
        Self {
            right_only,
            left_only,
            intersection,
        }
    }
}

fn intersect_maps(a: &Map<String, Value>, b: &Map<String, Value>) -> MapDifference {
    let mut intersection = HashSet::new();
    let mut left = HashSet::new();
    let mut right = HashSet::new();
    for a_key in a.keys() {
        if b.contains_key(a_key) {
            intersection.insert(String::from(a_key));
        } else {
            left.insert(String::from(a_key));
        }
    }
    for b_key in b.keys() {
        if !a.contains_key(b_key) {
            right.insert(String::from(b_key));
        }
    }
    let left = if left.is_empty() { None } else { Some(left) };
    let right = if right.is_empty() { None } else { Some(right) };
    let intersection = if intersection.is_empty() {
        None
    } else {
        Some(intersection)
    };
    MapDifference::new(left, right, intersection)
}

#[cfg(test)]
mod tests {
    use super::*;
    use maplit::hashmap;
    use serde_json::json;

    #[test]
    fn test_arrays_simple_diff() {
        let data1 = r#"["a","b","c"]"#;
        let data2 = r#"["a","b","d"]"#;
        let diff = compare_jsons(data1, data2).unwrap();
        assert_eq!(diff.left_only_keys, KeyNode::Nil);
        assert_eq!(diff.right_only_keys, KeyNode::Nil);
        let diff = diff.keys_in_both.absolute_keys_to_vec(None);
        assert_eq!(diff.len(), 1);
        assert_eq!(
            diff.first().unwrap().to_string(),
            r#"[l: 2]  -> { "c" != "d" }"#
        );
    }

    #[test]
    fn test_arrays_more_complex_diff() {
        let data1 = r#"["a","b","c"]"#;
        let data2 = r#"["a","a","b","d"]"#;
        let diff = compare_jsons(data1, data2).unwrap();

        let changes_diff = diff.keys_in_both.absolute_keys_to_vec(None);
        assert_eq!(diff.left_only_keys, KeyNode::Nil);

        assert_eq!(changes_diff.len(), 1);
        assert_eq!(
            changes_diff.first().unwrap().to_string(),
            r#"[l: 2]  -> { "c" != "d" }"#
        );
        let insertions = diff.right_only_keys.absolute_keys_to_vec(None);
        assert_eq!(insertions.len(), 1);
        assert_eq!(insertions.first().unwrap().to_string(), r#" [l: 0] - "a""#);
    }

    #[test]
    fn test_arrays_extra_left() {
        let data1 = r#"["a","b","c"]"#;
        let data2 = r#"["a","b"]"#;
        let diff = compare_jsons(data1, data2).unwrap();

        let diffs = diff.left_only_keys.absolute_keys_to_vec(None);
        assert_eq!(diffs.len(), 1);
        assert_eq!(diffs.first().unwrap().to_string(), r#" [l: 2] - "c""#);
        assert_eq!(diff.keys_in_both, KeyNode::Nil);
        assert_eq!(diff.right_only_keys, KeyNode::Nil);
    }

    #[test]
    fn test_arrays_extra_right() {
        let data1 = r#"["a","b"]"#;
        let data2 = r#"["a","b","c"]"#;
        let diff = compare_jsons(data1, data2).unwrap();

        let diffs = diff.right_only_keys.absolute_keys_to_vec(None);
        assert_eq!(diffs.len(), 1);
        assert_eq!(diffs.first().unwrap().to_string(), r#" [l: 2] - "c""#);
        assert_eq!(diff.keys_in_both, KeyNode::Nil);
        assert_eq!(diff.left_only_keys, KeyNode::Nil);
    }

    #[test]
    fn test_arrays_object_extra() {
        let data1 = r#"["a","b"]"#;
        let data2 = r#"["a","b", {"c": {"d": "e"} }]"#;
        let diff = compare_jsons(data1, data2).unwrap();

        let diffs = diff.right_only_keys.absolute_keys_to_vec(None);
        assert_eq!(diffs.len(), 1);
        assert_eq!(
            diffs.first().unwrap().to_string(),
            r#" [l: 2] - {"c":{"d":"e"}}"#
        );
        assert_eq!(diff.keys_in_both, KeyNode::Nil);
        assert_eq!(diff.left_only_keys, KeyNode::Nil);
    }

    #[test]
    fn nested_diff() {
        let data1 = r#"{
            "a":"b",
            "b":{
                "c":{
                    "d":true,
                    "e":5,
                    "f":9,
                    "h":{
                        "i":true,
                        "j":false
                    }
                }
            }
        }"#;
        let data2 = r#"{
            "a":"b",
            "b":{
                "c":{
                    "d":true,
                    "e":6,
                    "g":0,
                    "h":{
                        "i":false,
                        "k":false
                    }
                }
            }
        }"#;

        let expected_left = KeyNode::Node(hashmap! {
        "b".to_string() => KeyNode::Node(hashmap! {
                "c".to_string() => KeyNode::Node(hashmap! {
                        "f".to_string() => KeyNode::Nil,
                        "h".to_string() => KeyNode::Node( hashmap! {
                                "j".to_string() => KeyNode::Nil,
                            }
                        ),
                }
                ),
            }),
        });
        let expected_right = KeyNode::Node(hashmap! {
            "b".to_string() => KeyNode::Node(hashmap! {
                    "c".to_string() => KeyNode::Node(hashmap! {
                            "g".to_string() => KeyNode::Nil,
                            "h".to_string() => KeyNode::Node(hashmap! {
                                    "k".to_string() => KeyNode::Nil,
                                }
                            )
                        }
                    )
                }
            )
        });
        let expected_uneq = KeyNode::Node(hashmap! {
            "b".to_string() => KeyNode::Node(hashmap! {
                    "c".to_string() => KeyNode::Node(hashmap! {
                            "e".to_string() => KeyNode::Value(json!(5), json!(6)),
                            "h".to_string() => KeyNode::Node(hashmap! {
                                    "i".to_string() => KeyNode::Value(json!(true), json!(false)),
                                }
                            )
                        }
                    )
                }
            )
        });
        let expected = Mismatch::new(expected_left, expected_right, expected_uneq);

        let mismatch = compare_jsons(data1, data2).unwrap();
        assert_eq!(mismatch, expected, "Diff was incorrect.");
    }

    #[test]
    fn no_diff() {
        let data1 = r#"{
            "a":"b",
            "b":{
                "c":{
                    "d":true,
                    "e":5,
                    "f":9,
                    "h":{
                        "i":true,
                        "j":false
                    }
                }
            }
        }"#;
        let data2 = r#"{
            "a":"b",
            "b":{
                "c":{
                    "d":true,
                    "e":5,
                    "f":9,
                    "h":{
                        "i":true,
                        "j":false
                    }
                }
            }
        }"#;

        assert_eq!(
            compare_jsons(data1, data2).unwrap(),
            Mismatch::new(KeyNode::Nil, KeyNode::Nil, KeyNode::Nil)
        );
    }

    #[test]
    fn no_json() {
        let data1 = r#"{}"#;
        let data2 = r#"{}"#;

        assert_eq!(
            compare_jsons(data1, data2).unwrap(),
            Mismatch::new(KeyNode::Nil, KeyNode::Nil, KeyNode::Nil)
        );
    }

    #[test]
    fn parse_err_source_one() {
        let invalid_json1 = r#"{invalid: json}"#;
        let valid_json2 = r#"{"a":"b"}"#;
        match compare_jsons(invalid_json1, valid_json2) {
            Ok(_) => panic!("This shouldn't be an Ok"),
            Err(err) => {
                matches!(err, Error::JSON(_));
            }
        };
    }

    #[test]
    fn parse_err_source_two() {
        let valid_json1 = r#"{"a":"b"}"#;
        let invalid_json2 = r#"{invalid: json}"#;
        match compare_jsons(valid_json1, invalid_json2) {
            Ok(_) => panic!("This shouldn't be an Ok"),
            Err(err) => {
                matches!(err, Error::JSON(_));
            }
        };
    }
}