diffus/diffable_impls/
set.rs

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
use crate::{
    edit::{set, Edit},
    Diffable,
};

macro_rules! set_impl {
    ($(($typ:ident, $key_constraint:ident, $diff_type:ident)),*) => {
        $(
            impl<'a, K: Diffable<'a> + Eq + $key_constraint + 'a> Diffable<'a> for $typ<K> {
                type Diff = $diff_type<&'a K, set::Edit<'a, K>>;

                fn diff(&'a self, other: &'a Self) -> Edit<Self> {
                    let intersection = self
                        .iter()
                        .filter(|k| other.contains(*k));

                    let unique_self = self.iter().filter(|k| !other.contains(*k));

                    let unique_other = other.iter().filter(|k| !self.contains(*k));

                    let value_diffs = unique_other
                        .map(|k| (k, set::Edit::Insert(k)))
                        .chain(unique_self.map(|k| (k, set::Edit::Remove(k))))
                        .chain(intersection.map(|k| (k, set::Edit::Copy(k))))
                        .collect::<$diff_type<_, _>>();

                    if value_diffs.iter().any(|(_, edit)| !edit.is_copy()) {
                        Edit::Change(value_diffs)
                    } else {
                        Edit::Copy(self)
                    }
                }
            }
        )*
    }
}

use std::{
    collections::{BTreeMap, BTreeSet, HashMap, HashSet},
    hash::Hash,
};
set_impl! {
    (BTreeSet, Ord, BTreeMap),
    (HashSet, Hash, HashMap)
}

#[cfg(feature = "indexmap-impl")]
use indexmap::{IndexMap, IndexSet};
#[cfg(feature = "indexmap-impl")]
set_impl! { (IndexSet, Hash, IndexMap) }

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn example() {
        let unity: std::collections::HashSet<_, _> = [1, 2, 3].iter().cloned().collect();
        let not_unity: std::collections::HashSet<_, _> = [1, 2, 4].iter().cloned().collect();

        if let Edit::Change(diff) = unity.diff(&not_unity) {
            assert!(diff[&1].is_copy());
            assert!(diff[&2].is_copy());
            assert!(diff[&3].is_remove());
            assert_eq!(diff[&4].insert().unwrap(), &4);
        } else {
            unreachable!()
        }
    }
}