pijul_org / pijul

Diff algorithms (as a separated crate)

By pmeunier on November 29, 2018
This patch is not signed.
8Fviczf3R1U8ncVX2qJDjVP3iNg1hj4Zj5S33EFqpsK5njQyFsDWXbxLVdsSxi57xbfZtJm6yd1qkC3fV1a6RFUx
This patch is in the following branches:
latest
master
testing

1
2
3
4
5
6
7
8
9
version = "0.1.0"
[package]
name = "diffs"
description = "A number of diff algorithms, also called longest common subsequence."
documentation = "https://docs.rs/diffs"
homepage = "https://nest.pijul.com/pijul_org/pijul"
version = "0.3.0"
license = "MIT/Apache-2.0"
authors = ["Pierre-√Čtienne Meunier <pe@pijul.org>"]
include = ["Cargo.toml", "src/lib.rs", "src/replace.rs", "src/patience.rs", "src/myers.rs", "src/test.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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
    fn equal(&mut self, old: usize, new: usize, len: usize) {}
    fn delete(&mut self, old: usize, len: usize) {}
    fn insert(&mut self, old: usize, new: usize, new_len: usize) {}
    fn replace(&mut self, old: usize, old_len: usize, new: usize, new_len: usize) {
        self.delete(old, old_len);
        self.insert(old + old_len, new, new_len);
    fn finish(&mut self) {}
    fn equal(&mut self, old: usize, new: usize, len: usize) {
    fn delete(&mut self, old: usize, len: usize) {
    fn insert(&mut self, old: usize, new: usize, new_len: usize) {
    fn replace(&mut self, old: usize, old_len: usize, new: usize, new_len: usize) {
    fn finish(&mut self) {
//! Various diff (longest common subsequence) algorithms, used in
//! practice:
//!
//! - Myers' diff, in time O((N+M)D) and space O(N+M), where N and M
//! are the sizes of the old and new version, respectively. See [the
//! original article by Eugene
//! W. Myers](http://www.xmailserver.org/diff2.pdf).
//!
//! - Patience diff, in time O(N log N + M log M + (N+M)D), and space
//! O(N+M), which tends to give more human-readable outputs. See [Bram
//! Cohen's blog post describing
//! it](https://bramcohen.livejournal.com/73318.html).

mod replace;
pub use replace::*;
/// Myers' diff algorithm
pub mod myers;
/// Patience diff algorithm
pub mod patience;

pub use myers::diff;

#[cfg(test)]
mod test;

#[allow(unused_variables)]
/// A trait for reacting to an edit script from the "old" version to
/// the "new" version.
pub trait Diff: Sized {
    type Error;
    /// Called when lines with indices `old` (in the old version) and
    /// `new` (in the new version) start an section equal in both
    /// versions, of length `len`.
    fn equal(&mut self, old: usize, new: usize, len: usize) -> Result<(), Self::Error> {
        Ok(())
    }
    /// Called when a section of length `len`, starting at `old`,
    /// needs to be deleted from the old version.
    fn delete(&mut self, old: usize, len: usize) -> Result<(), Self::Error> {
        Ok(())
    }
    /// Called when a section of the new version, of length `new_len`
    /// and starting at `new`, needs to be inserted at position `old'.
    fn insert(&mut self, old: usize, new: usize, new_len: usize) -> Result<(), Self::Error> {
        Ok(())
    }
    /// Called when a section of the old version, starting at index
    /// `old` and of length `old_len`, needs to be replaced with a
    /// section of length `new_len`, starting at `new`, of the new
    /// version.
    fn replace(
        &mut self,
        old: usize,
        old_len: usize,
        new: usize,
        new_len: usize,
    ) -> Result<(), Self::Error> {
        self.delete(old, old_len)?;
        self.insert(old, new, new_len)
    }
    /// Always called at the end of the algorithm.
    fn finish(&mut self) -> Result<(), Self::Error> {
        Ok(())
    }
}

impl<'a, D: Diff + 'a> Diff for &'a mut D {
    type Error = D::Error;
    fn equal(&mut self, old: usize, new: usize, len: usize) -> Result<(), Self::Error> {
        (*self).equal(old, new, len)
    }
    fn delete(&mut self, old: usize, len: usize) -> Result<(), Self::Error> {
        (*self).delete(old, len)
    }

    fn insert(&mut self, old: usize, new: usize, new_len: usize) -> Result<(), Self::Error> {
        (*self).insert(old, new, new_len)
    }

    fn replace(
        &mut self,
        old: usize,
        old_len: usize,
        new: usize,
        new_len: usize,
    ) -> Result<(), Self::Error> {
        (*self).replace(old, old_len, new, new_len)
    }

    fn finish(&mut self) -> Result<(), Self::Error> {
        (*self).finish()
    }
}


































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
    if a >= 0 {
        (a as usize) % b
    } else {
        let q = a / (b as isize);
        (a - (b as isize) * (q - 1)) as usize
    }
/// Myers' diff algorithm.
pub fn diff<A, B: PartialEq<A>, D: Diff>(d: &mut D, e: &[A], f: &[B]) {
    diff_offsets(d, e, f, 0, 0);
pub(crate) fn diff_offsets<D: Diff + ?Sized, A, B: PartialEq<A>>(
    e: &[A],
    f: &[B],
) {
    let n = e.len();
    let m = f.len();
    let l = (n + m) as isize;
    let z = (2 * min(n, m) + 2) as usize;
    if n > 0 && m > 0 {
                            f[f_i] == e[e_i]
                                diff_offsets(diff, &e[0..x], &f[0..y], i, j);
                                    diff.equal(i + x, j + y, u-x);
                                diff_offsets(diff, &e[u..n], &f[v..m], i+u, j+v);
                                return
                                diff.equal(i, j, n);
                                diff.insert(i+n, j+n, m-n);
                                return
                                diff.equal(i, j, m);
                                diff.delete(i+m, n-m);
                                return
                                return
    } else if n > 0 {
        diff.delete(i, n)
    } else if m > 0 {
        diff.insert(i, j, m)
use std::cmp::{max, min};
use std::ops::Index;
use Diff;

fn modulo(a: isize, b: usize) -> usize {
    let b = b as isize;
    (((a % b) + b) % b) as usize
}

#[test]
fn test_modulo() {
    assert_eq!(modulo(-11, 10), 9);
    assert_eq!(modulo(23, 7), 2);
    assert_eq!(modulo(-12, 6), 0);
}

/// Myers' diff algorithm. Diff `e`, between indices `e0` (included)
/// and `e1` (excluded), on the one hand, and `f`, between indices
/// `f0` (included)` and `f1` (excluded), on the other hand.
pub fn diff<S: Index<usize> + ?Sized, T: Index<usize> + ?Sized, D: Diff>(
    d: &mut D,
    e: &S,
    e0: usize,
    e1: usize,
    f: &T,
    f0: usize,
    f1: usize,
) -> Result<(), D::Error>
where
    T::Output: PartialEq<S::Output>,
{
    diff_offsets(d, e, e0, e1, f, f0, f1)?;
    d.finish()
}

pub(crate) fn diff_offsets<D: Diff + ?Sized, S: Index<usize> + ?Sized, T: Index<usize> + ?Sized>(
    diff: &mut D,
    e: &S,
    i: usize,
    i_: usize,
    f: &T,
    j: usize,
    j_: usize,
) -> Result<(), D::Error>
where
    T::Output: PartialEq<S::Output>,
{
    if i_ > i && j_ > j {
        let n = i_ - i;
        let m = j_ - j;
        let l = (n + m) as isize;
        let z = (2 * min(n, m) + 2) as usize;
        let w = n as isize - m as isize;
        let mut g = vec![0; z as usize];
        let mut p = vec![0; z as usize];
        for h in 0..=(l / 2 + l % 2) {
            macro_rules! search {
                ($e: expr, $c: expr, $d: expr) => {
                    let (k0, k1) = {
                        let (m, n) = (m as isize, n as isize);
                        (-(h - 2*max(0, h - m)), h-2*max(0, h-n)+1)
                    };
                    for k in (k0..k1).step_by(2) {
                        let mut a: usize = if k == -h || k != h && $c[modulo(k-1, z)] < $c[modulo(k+1, z)] {
                            $c[modulo(k+1, z)]
                        } else {
                            $c[modulo(k-1, z)] + 1
                        };
                        let mut b = (a as isize - k) as usize;
                        let (s, t) = (a, b);
                        while a < n && b < m && {
                            let (e_i, f_i) = if $e { (a, b) } else { (n - a - 1, m - b - 1) };
                            f[j + f_i] == e[i + e_i]
                        } {
                            a += 1;
                            b += 1;
                        }
                        $c[modulo(k, z)] = a;
                        let bound = if $e { h-1 } else { h };
                        if (l%2 == 1) == $e
                            && w-k >= -bound && w-k <= bound
                            && $c[modulo(k, z)]+$d[modulo(w-k, z)] >= n
                        {
                            let (x, y, u, v) = if $e {
                                (s, t, a, b)
                            } else {
                                (n-a, m-b, n-s, m-t)
                            };
                            if h + bound > 1 || (x != u && y != v) {
                                diff_offsets(diff, e, i, i+x, f, j, j+y)?;
                                if x != u {
                                    diff.equal(i + x, j + y, u-x)?;
                                }
                                diff_offsets(diff, e, i+u, i_, f, j+v, j_)?;
                                return Ok(())
                            } else if m > n {
                                diff.equal(i, j, n)?;
                                diff.insert(i+n, j+n, m-n)?;
                                return Ok(())
                            } else if m < n {
                                diff.equal(i, j, m)?;
                                diff.delete(i+m, n-m)?;
                                return Ok(())
                            } else {
                                return Ok(())
                            }
                        }
                    }
                }
            }
            search!(true, g, p);
            search!(false, p, g);
        }
    } else if i_ > i {
        diff.delete(i, i_ - i)?
    } else if j_ > j {
        diff.insert(i, j, j_ - j)?
    }
    Ok(())
}






















































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
use {myers, Diff, Replace};
struct I<'a, A: 'a> {
    p: &'a [A],
#[cfg(test)]
impl<'a, A: std::fmt::Debug + 'a> std::fmt::Debug for I<'a, A> {
        write!(fmt, "{:?}", self.p[self.i])
impl<'a, 'b, A: 'a, B: PartialEq<A> + 'b> PartialEq<I<'a, A>> for I<'b, B> {
fn unique<A: Hash + Eq>(p: &[A]) -> Vec<I<A>> {
    for (i, a) in p.iter().enumerate() {
        match aa.entry(a) {
    A: Hash + Eq, // + std::fmt::Debug,
    B: Hash + Eq + PartialEq<A>, // + std::fmt::Debug,
    a: &[A],
    b: &[B],
) {
    let au = unique(a);
    let bu = unique(b);
    struct Patience<'a, 'b, 'd, A: 'a, B: 'b, D: Diff + 'd> {
        a: &'a [A],
        b: &'b [B],
        au: &'a [I<'a, A>],
        bu: &'b [I<'b, B>],
            'b,
            'd,
            A: 'a, // + std::fmt::Debug,
            B: 'b + PartialEq<A>, // + std::fmt::Debug,
            D: Diff + 'd,
        > Diff for Patience<'a, 'b, 'd, A, B, D>
        fn equal(&mut self, old: usize, new: usize, len: usize) {
                let a = &self.a[self.current_a..self.au[old].i];
                let b = &self.b[self.current_b..self.bu[new].i];
                myers::diff_offsets(self.d, a, b, self.current_a, self.current_b);
        fn finish(&mut self) {
            let a = &self.a[self.current_a..];
            let b = &self.b[self.current_b..];
            myers::diff_offsets(self.d, a, b, self.current_a, self.current_b);
            self.d.finish()
        current_a: 0,
        current_b: 0,
        a,
        b,
    myers::diff(&mut d, &au, &bu);
    struct D {}
        fn equal(&mut self, o: usize, n: usize, len: usize) {
            println!("equal {:?} {:?} {:?}", o, n, len);
        }
        fn delete(&mut self, o: usize, len: usize) {
            println!("delete {:?} {:?}", o, len);
        fn insert(&mut self, o: usize, n: usize, len: usize) {
            println!("insert {:?} {:?} {:?}", o, n, len);
        fn replace(&mut self, o: usize, l: usize, n: usize, nl: usize) {
            println!("replace {:?} {:?} {:?} {:?}", o, l, n, nl);
    let mut d = Replace::new(D {});
    diff(&mut d, a, b);
use std::collections::hash_map::Entry;
use std::collections::HashMap;
use std::hash::Hash;
use std::ops::Index;
use {myers, Diff, Replace};

struct I<'a, S: 'a + Index<usize> + ?Sized> {
    p: &'a S,
    i: usize,
}

impl<'a, A: Index<usize> + 'a> std::fmt::Debug for I<'a, A>
where
    A::Output: std::fmt::Debug,
{
    fn fmt(&self, fmt: &mut std::fmt::Formatter) -> std::fmt::Result {
        write!(fmt, "{:?}", &self.p[self.i])
    }
}

impl<'a, 'b, A: Index<usize> + 'b + ?Sized, B: Index<usize> + 'b + ?Sized> PartialEq<I<'a, A>>
    for I<'b, B>
where
    B::Output: PartialEq<A::Output>,
{
    fn eq(&self, b: &I<'a, A>) -> bool {
        self.p[self.i] == b.p[b.i]
    }
}

fn unique<A: Hash + Eq, S: Index<usize, Output = A> + ?Sized>(
    p: &S,
    e0: usize,
    e1: usize,
) -> Vec<I<S>> {
    let mut aa = HashMap::new();
    for i in e0..e1 {
        match aa.entry(&p[i]) {
            Entry::Vacant(e) => {
                e.insert(Some(i));
            }
            Entry::Occupied(mut e) => {
                let e = e.get_mut();
                if e.is_some() {
                    *e = None
                }
            }
        }
    }
    let mut v: Vec<_> = aa
        .into_iter()
        .filter_map(|(_, x)| x)
        .map(|i| I { p, i })
        .collect();
    v.sort_by(|a, b| a.i.cmp(&b.i));
    v
}

/// Patience diff algorithm.
pub fn diff<
    A: Hash + Eq,
    B: Hash + Eq + PartialEq<A>,
    S: Index<usize, Output = A> + ?Sized,
    T: Index<usize, Output = B> + ?Sized,
    D: Diff,
>(
    d: &mut D,
    e: &S,
    e0: usize,
    e1: usize,
    f: &T,
    f0: usize,
    f1: usize,
) -> Result<(), D::Error> {
    let au = unique(e, e0, e1);
    let bu = unique(f, f0, f1);

    struct Patience<
        'a,
        'b,
        'd,
        S: 'a + Index<usize> + ?Sized,
        T: 'b + Index<usize> + ?Sized,
        D: Diff + 'd,
    > {
        current_a: usize,
        current_b: usize,
        a1: usize,
        b1: usize,
        a: &'a S,
        b: &'b T,
        d: &'d mut D,
        au: &'a [I<'a, S>],
        bu: &'b [I<'b, T>],
    }
    impl<
            'a,
            'b,
            'd,
            S: 'a + Index<usize> + ?Sized,
            T: 'b + Index<usize> + ?Sized,
            D: Diff + 'd,
        > Diff for Patience<'a, 'b, 'd, S, T, D>
    where
        T::Output: PartialEq<S::Output>,
    {
        type Error = D::Error;
        fn equal(&mut self, old: usize, new: usize, len: usize) -> Result<(), D::Error> {
            // eprintln!("equal {:?} {:?} {:?}", old, new, len);
            for (old, new) in (old..old + len).zip(new..new + len) {
                let a0 = self.current_a;
                let b0 = self.current_b;
                while self.current_a < self.au[old].i
                    && self.current_b < self.bu[new].i
                    && self.b[self.current_b] == self.a[self.current_a]
                {
                    self.current_a += 1;
                    self.current_b += 1;
                }
                if self.current_a > a0 {
                    self.d.equal(a0, b0, self.current_a - a0)?
                }
                // let a = &self.a[self.current_a..self.au[old].i];
                // let b = &self.b[self.current_b..self.bu[new].i];
                // eprintln!("matching a: {:?} {:?}", self.current_a, self.au[old].i);
                // eprintln!("matching b: {:?} {:?}", self.current_b, self.bu[new].i);
                myers::diff_offsets(
                    self.d,
                    self.a,
                    self.current_a,
                    self.au[old].i,
                    self.b,
                    self.current_b,
                    self.bu[new].i,
                )?;
                self.current_a = self.au[old].i;
                self.current_b = self.bu[new].i;
            }
            Ok(())
        }
        /*
        fn insert(&mut self, old: usize, new: usize, len: usize) -> Result<(), D::Error> {
            eprintln!("insert {:?} {:?} {:?}", old, new, len);
            Ok(())
        }
        fn delete(&mut self, old: usize, len: usize) -> Result<(), D::Error> {
            eprintln!("delete {:?} {:?}", old, len);
            Ok(())
        }
        fn replace(
            &mut self,
            old: usize,
            len: usize,
            new: usize,
            new_len: usize,
        ) -> Result<(), D::Error> {
            eprintln!("replace {:?} {:?} {:?} {:?}", old, len, new, new_len);
            Ok(())
        }
        */
        fn finish(&mut self) -> Result<(), D::Error> {
            myers::diff(
                self.d,
                self.a,
                self.current_a,
                self.a1,
                self.b,
                self.current_b,
                self.b1,
            )
        }
    }
    let mut d = Replace::new(Patience {
        current_a: e0,
        current_b: f0,
        a: e,
        a1: e1,
        b: f,
        b1: f1,
        d,
        au: &au,
        bu: &bu,
    });
    myers::diff(&mut d, &au, 0, au.len(), &bu, 0, bu.len())?;
    Ok(())
}

#[test]
fn patience() {
    let a: &[usize] = &[11, 1, 2, 2, 3, 4, 4, 4, 5, 47, 19];
    let b: &[usize] = &[10, 1, 2, 2, 8, 9, 4, 4, 7, 47, 18];
    struct D(Vec<(usize, usize, usize, usize)>);
    impl Diff for D {
        type Error = ();
        fn delete(&mut self, o: usize, len: usize) -> Result<(), ()> {
            self.0.push((o, len, 0, 0));
            Ok(())
        }
        fn insert(&mut self, o: usize, n: usize, len: usize) -> Result<(), ()> {
            self.0.push((o, 0, n, len));
            Ok(())
        }
        fn replace(&mut self, o: usize, l: usize, n: usize, nl: usize) -> Result<(), ()> {
            self.0.push((o, l, n, nl));
            Ok(())
        }
    }
    let mut d = Replace::new(D(Vec::new()));
    diff(&mut d, a, 0, a.len(), b, 0, b.len()).unwrap();
    let d: D = d.into_inner();
    assert_eq!(
        d.0.as_slice(),
        &[(0, 1, 0, 1), (4, 2, 4, 2), (8, 1, 8, 1), (10, 1, 10, 1)]
    );
}





















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
pub struct Replace<D:Diff> {
impl<D:Diff> Replace<D> {

impl<D:Diff> Diff for Replace<D> {
    fn equal(&mut self, old: usize, new: usize, len: usize) {
                self.d.replace(old0, len0, new1, new_len1)
                self.d.delete(old0, len0);
            self.d.insert(old0, new0, new_len0);
    fn delete(&mut self, old: usize, len: usize) {
            self.d.equal(a, b, c)
            self.del = Some((old0, len0+len))
    fn insert(&mut self, old: usize, new: usize, new_len: usize) {
            self.d.equal(a, b, c)
            assert_eq!(new1+new_len1, new);
    fn replace(&mut self, old: usize, old_len: usize, new: usize, new_len: usize) {
            self.d.equal(a, b, c)
    fn finish(&mut self) {
                self.d.replace(old0, len0, new1, new_len1)
                self.d.delete(old0, len0);
            self.d.insert(old0, new0, new_len0);
        self.d.finish();
use Diff;

/// A "differ" that combines deletions and insertions to give blocks
/// of maximal length, and replacements when appropriate.
pub struct Replace<D: Diff> {
    d: D,
    del: Option<(usize, usize)>,
    ins: Option<(usize, usize, usize)>,
    eq: Option<(usize, usize, usize)>,
}

impl<D: Diff> Replace<D> {
    pub fn new(d: D) -> Self {
        Replace {
            d,
            del: None,
            ins: None,
            eq: None,
        }
    }
    pub fn into_inner(self) -> D {
        self.d
    }
}

impl<D: Diff> AsRef<D> for Replace<D> {
    fn as_ref(&self) -> &D {
        &self.d
    }
}

impl<D: Diff> AsMut<D> for Replace<D> {
    fn as_mut(&mut self) -> &mut D {
        &mut self.d
    }
}

impl<D: Diff> Diff for Replace<D> {
    type Error = D::Error;
    fn equal(&mut self, old: usize, new: usize, len: usize) -> Result<(), D::Error> {
        if let Some((old0, len0)) = self.del.take() {
            if let Some((_, new1, new_len1)) = self.ins.take() {
                self.d.replace(old0, len0, new1, new_len1)?
            } else {
                self.d.delete(old0, len0)?
            }
        } else if let Some((old0, new0, new_len0)) = self.ins.take() {
            self.d.insert(old0, new0, new_len0)?
        }

        if let Some((a, b, c)) = self.eq.take() {
            self.eq = Some((a, b, c + len))
        } else {
            self.eq = Some((old, new, len))
        }
        Ok(())
    }
    fn delete(&mut self, old: usize, len: usize) -> Result<(), D::Error> {
        if let Some((a, b, c)) = self.eq.take() {
            self.d.equal(a, b, c)?
        }
        if let Some((old0, len0)) = self.del.take() {
            assert_eq!(old, old0 + len0);
            self.del = Some((old0, len0 + len))
        } else {
            self.del = Some((old, len))
        }
        Ok(())
    }

    fn insert(&mut self, old: usize, new: usize, new_len: usize) -> Result<(), D::Error> {
        if let Some((a, b, c)) = self.eq.take() {
            self.d.equal(a, b, c)?
        }
        if let Some((old1, new1, new_len1)) = self.ins.take() {
            assert_eq!(new1 + new_len1, new);
            self.ins = Some((old1, new1, new_len + new_len1))
        } else {
            self.ins = Some((old, new, new_len))
        }
        Ok(())
    }

    fn replace(
        &mut self,
        old: usize,
        old_len: usize,
        new: usize,
        new_len: usize,
    ) -> Result<(), D::Error> {
        if let Some((a, b, c)) = self.eq.take() {
            self.d.equal(a, b, c)?
        }
        self.d.replace(old, old_len, new, new_len)
    }

    fn finish(&mut self) -> Result<(), D::Error> {
        if let Some((a, b, c)) = self.eq.take() {
            self.d.equal(a, b, c)?
        }
        if let Some((old0, len0)) = self.del.take() {
            if let Some((_, new1, new_len1)) = self.ins.take() {
                self.d.replace(old0, len0, new1, new_len1)?
            } else {
                self.d.delete(old0, len0)?
            }
        } else if let Some((old0, new0, new_len0)) = self.ins.take() {
            self.d.insert(old0, new0, new_len0)?
        }
        self.d.finish()
    }
}

#[test]
fn myers() {
    use myers;
    let a: &[&str] = &[
        ">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n",
        "a\n",
        "b\n",
        "c\n",
        "================================\n",
        "d\n",
        "e\n",
        "f\n",
        "<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\n",
    ];
    let b: &[&str] = &[
        ">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n",
        "x\n",
        "b\n",
        "c\n",
        "================================\n",
        "y\n",
        "e\n",
        "f\n",
        "<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\n",
    ];

    struct D {}
    impl Diff for D {
        type Error = ();
        fn equal(&mut self, o: usize, n: usize, len: usize) -> Result<(), ()> {
            println!("equal {:?} {:?} {:?}", o, n, len);
            Ok(())
        }
        fn delete(&mut self, o: usize, len: usize) -> Result<(), ()> {
            println!("delete {:?} {:?}", o, len);
            Ok(())
        }
        fn insert(&mut self, o: usize, n: usize, len: usize) -> Result<(), ()> {
            println!("insert {:?} {:?} {:?}", o, n, len);
            Ok(())
        }
        fn replace(&mut self, o: usize, l: usize, n: usize, nl: usize) -> Result<(), ()> {
            println!("replace {:?} {:?} {:?} {:?}", o, l, n, nl);
            Ok(())
        }
    }
    let mut d = Replace::new(D {});
    myers::diff(&mut d, a, 0, a.len(), b, 0, b.len()).unwrap();
}























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
use {Diff, Replace, myers};
    let a: &[usize] = &[0,1,2,3,4];
    let b: &[usize] = &[0,1,2,9,4];
        fn delete(&mut self, o: usize, len: usize) {
        fn insert(&mut self, o: usize, n: usize, len: usize) {
            assert_eq!(o, 4);
    myers::diff(&mut diff, a, b)
    let a: &[usize] = &[0,1,2,3,4,4,4,5];
    let b: &[usize] = &[0,1,2,8,9,4,4,7];
        fn delete(&mut self, _o: usize, _len: usize) {
            panic!("Should not delete");
        fn insert(&mut self, _o: usize, _n: usize, _len: usize) {
            panic!("Should not insert");
        fn replace(&mut self, o: usize, l: usize, n: usize, nl: usize) {
    let mut diff = Replace::new(D{});
    myers::diff(&mut diff, a, b);
    let a: &[usize] = &[0,1,2,3,4];
    let b: &[usize] = &[0,1,2,7,8,9];
        fn delete(&mut self, _o: usize, _len: usize) {
        fn insert(&mut self, _o: usize, _n: usize, _len: usize) {
        fn replace(&mut self, _o: usize, _l: usize, _n: usize, _nl: usize) {
    let mut diff = Replace::new(D{});
    myers::diff(&mut diff, a, b);
use {myers, Diff, Replace};

#[test]
fn test_diff() {
    let a: &[usize] = &[0, 1, 2, 3, 4];
    let b: &[usize] = &[0, 1, 2, 9, 4];
    struct D {}
    impl Diff for D {
        type Error = ();
        fn delete(&mut self, o: usize, len: usize) -> Result<(), ()> {
            assert_eq!(o, 3);
            assert_eq!(len, 1);
            println!("delete");
            Ok(())
        }
        fn insert(&mut self, o: usize, n: usize, len: usize) -> Result<(), ()> {
            assert_eq!(o, 3);
            assert_eq!(n, 3);
            assert_eq!(len, 1);
            println!("insert");
            Ok(())
        }
    }
    let mut diff = Replace::new(D {});
    myers::diff(&mut diff, a, 0, a.len(), b, 0, b.len()).unwrap()
}

#[test]
fn test_contiguous() {
    let a: &[usize] = &[0, 1, 2, 3, 4, 4, 4, 5];
    let b: &[usize] = &[0, 1, 2, 8, 9, 4, 4, 7];
    struct D {}
    impl Diff for D {
        type Error = ();
        fn delete(&mut self, _o: usize, _len: usize) -> Result<(), ()> {
            panic!("Should not delete")
        }
        fn insert(&mut self, _o: usize, _n: usize, _len: usize) -> Result<(), ()> {
            panic!("Should not insert")
        }
        fn replace(&mut self, o: usize, l: usize, n: usize, nl: usize) -> Result<(), ()> {
            assert!(o != 3 || (l == 2 && nl == 2));
            assert!(o != 7 || (l == 1 && nl == 1));
            println!("replace {:?} {:?} {:?} {:?}", o, l, n, nl);
            Ok(())
        }
    }
    let mut diff = Replace::new(D {});
    myers::diff(&mut diff, a, 0, a.len(), b, 0, b.len()).unwrap();
}

#[test]
fn test_replace() {
    let a: &[usize] = &[0, 1, 2, 3, 4];
    let b: &[usize] = &[0, 1, 2, 7, 8, 9];
    struct D {}
    impl Diff for D {
        type Error = ();
        fn delete(&mut self, _o: usize, _len: usize) -> Result<(), ()> {
            panic!("should not delete")
        }
        fn insert(&mut self, _o: usize, _n: usize, _len: usize) -> Result<(), ()> {
            panic!("should not insert")
        }
        fn replace(&mut self, _o: usize, _l: usize, _n: usize, _nl: usize) -> Result<(), ()> {
            Ok(())
        }
    }
    let mut diff = Replace::new(D {});
    myers::diff(&mut diff, a, 0, a.len(), b, 0, b.len()).unwrap();
}

#[test]
fn test_pat() {
    let a: &[usize] = &[0, 1, 3, 4, 5];
    let b: &[usize] = &[0, 1, 4, 5, 8, 9];
    struct D {}
    impl Diff for D {
        type Error = ();
        fn delete(&mut self, _o: usize, _len: usize) -> Result<(), ()> {
            println!("delete {:?} {:?}", _o, _len);
            Ok(())
        }
        fn insert(&mut self, _o: usize, _n: usize, _len: usize) -> Result<(), ()> {
            println!("insert {:?} {:?} {:?}", _o, _n, _len);
            Ok(())
        }
        fn replace(&mut self, _o: usize, _l: usize, _n: usize, _nl: usize) -> Result<(), ()> {
            println!("replace {:?} {:?} {:?} {:?}", _o, _l, _n, _nl);
            Ok(())
        }
    }
    let mut diff = Replace::new(D {});
    myers::diff(&mut diff, a, 0, a.len(), b, 0, b.len()).unwrap();
}