diffus/diffable_impls/
collection.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
71
72
73
74
use crate::{
    edit::{self, collection},
    Diffable, Same,
};

macro_rules! collection_impl {
    ($($typ:ident),*) => {
        $(
            impl<'a, T: Same + Diffable<'a> + 'a> Diffable<'a> for $typ<T> {
                type Diff = Vec<collection::Edit<'a, T, T::Diff>>;

                fn diff(&'a self, other: &'a Self) -> edit::Edit<Self> {

                    let s = crate::lcs::lcs_post_change(
                        crate::lcs::lcs(
                            || self.iter(),
                            || other.iter(),
                            self.len(),
                            other.len(),
                        )
                    )
                        .collect::<Vec<_>>();

                    if s.iter().all(collection::Edit::is_copy) {
                        edit::Edit::Copy(self)
                    } else {
                        edit::Edit::Change(s)
                    }
                }
            }
        )*
    }
}

use std::collections::{BinaryHeap, LinkedList, VecDeque};
collection_impl! {
    BinaryHeap, LinkedList, Vec, VecDeque
}

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

    #[test]
    fn diff() {
        use super::Diffable;

        let left = b"XMJYAUZ".to_vec();
        let right = b"MZJAWXU".to_vec();

        let diff = left.diff(&right);
        if let edit::Edit::Change(diff) = diff {
            use collection::Edit::*;

            assert_eq!(
                diff.into_iter().collect::<Vec<_>>(),
                vec![
                    Remove(&b'X'),
                    Copy(&b'M'),
                    Insert(&b'Z'),
                    Copy(&b'J'),
                    Remove(&b'Y'),
                    Copy(&b'A'),
                    Insert(&b'W'),
                    Insert(&b'X'),
                    Copy(&b'U'),
                    Remove(&b'Z')
                ]
            );
        } else {
            unreachable!()
        }
    }
}