slice-diff-patch 1.3.1

Library crate providing utility functions for diff and patch of slices
Documentation
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
443
444
445
446
447
448
449
450
#![doc = include_str!("../README.md")]

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

    fn display<T: PartialEq + Clone + Debug>(a: &[T], b: &[T], d: &[Change<T>]) {
        println!("a = {:?}", a);
        println!("b = {:?}", b);
        for i in d {
            println!("i = {:?}", i);
        }
    }

    fn test_states<T: PartialEq + Clone + Debug>(
        states: &[&[T]],
        diff: &dyn Fn(&[T], &[T]) -> Vec<Change<T>>,
    ) {
        for i in 0..states.len() - 1 {
            let a = &states[i];
            let b = &states[i + 1];
            let d = diff(&a, &b);
            display(&a, &b, &d);
            let c = patch(&a, &d);
            assert_eq!(&c, b);
        }
    }

    #[test]
    fn diff_int() {
        test_states(
            &[
                &[],
                &[2],
                &[2, 6],
                &[2, 4, 6],
                &[2, 4, 6, 8],
                &[1, 2, 4, 6, 8],
                &[1, 2, 3, 5, 8],
                &[1, 2, 3, 5, 8],
                &[2, 3, 5, 8],
                &[2, 5, 8],
                &[2, 5],
                &[],
            ],
            &diff_diff,
        );
    }

    #[test]
    fn diff_str() {
        test_states(
            &[
                &[],
                &["alpha"],
                &["alpha", "delta"],
                &["alpha", "bravo", "delta"],
                &["alpha", "bravo", "charlie", "delta"],
                &["pre-alpha", "alpha", "pre-bravo", "pre-charlie", "delta"],
                &["pre-alpha", "alpha", "pre-bravo", "pre-charlie"],
                &["pre-alpha", "pre-bravo", "pre-charlie"],
                &["pre-bravo", "pre-charlie"],
                &["pre-bravo"],
                &[],
            ],
            &diff_diff,
        );
    }

    #[test]
    fn lcs_int() {
        test_states(
            &[
                &[],
                &[2],
                &[2, 6],
                &[2, 4, 6],
                &[2, 4, 6, 8],
                &[1, 2, 4, 6, 8],
                &[1, 2, 3, 5, 8],
                &[1, 2, 3, 5, 8],
                &[2, 3, 5, 8],
                &[2, 5, 8],
                &[2, 5],
                &[],
            ],
            &lcs_diff,
        );
    }

    #[test]
    fn lcs_str() {
        test_states(
            &[
                &[],
                &["alpha"],
                &["alpha", "delta"],
                &["alpha", "bravo", "delta"],
                &["alpha", "bravo", "charlie", "delta"],
                &["pre-alpha", "alpha", "pre-bravo", "pre-charlie", "delta"],
                &["pre-alpha", "alpha", "pre-bravo", "pre-charlie"],
                &["pre-alpha", "pre-bravo", "pre-charlie"],
                &["pre-bravo", "pre-charlie"],
                &["pre-bravo"],
                &[],
            ],
            &lcs_diff,
        );
    }

    #[test]
    fn wu_int() {
        test_states(
            &[
                &[],
                &[2],
                &[2, 6],
                &[2, 4, 6],
                &[2, 4, 6, 8],
                &[1, 2, 4, 6, 8],
                &[1, 2, 3, 5, 8],
                &[1, 2, 3, 5, 8],
                &[2, 3, 5, 8],
                &[2, 5, 8],
                &[2, 5],
                &[],
            ],
            &wu_diff,
        );
    }

    #[test]
    fn wu_str() {
        test_states(
            &[
                &[],
                &["alpha"],
                &["alpha", "delta"],
                &["alpha", "bravo", "delta"],
                &["alpha", "bravo", "charlie", "delta"],
                &["pre-alpha", "alpha", "pre-bravo", "pre-charlie", "delta"],
                &["pre-alpha", "alpha", "pre-bravo", "pre-charlie"],
                &["pre-alpha", "pre-bravo", "pre-charlie"],
                &["pre-bravo", "pre-charlie"],
                &["pre-bravo"],
                &[],
            ],
            &wu_diff,
        );
    }

    fn update<T: PartialEq + Clone + Debug>(
        a: &[T],
        b: &[T],
        changes: Vec<Change<T>>,
        diff: &dyn Fn(&[T], &[T]) -> Vec<Change<T>>,
    ) {
        assert_eq!(diff(&a, &b), changes);
    }

    #[test]
    fn diff_update() {
        update(&[1], &[2], vec![Change::Update((0, 2))], &diff_diff);
        update(&[1, 2], &[1, 3], vec![Change::Update((1, 3))], &diff_diff);
        update(
            &[1, 2, 3],
            &[1, 2, 4],
            vec![Change::Update((2, 4))],
            &diff_diff,
        );
        update(
            &["alpha"],
            &["bravo"],
            vec![Change::Update((0, "bravo"))],
            &diff_diff,
        );
        update(
            &["alpha", "bravo"],
            &["alpha", "charlie"],
            vec![Change::Update((1, "charlie"))],
            &diff_diff,
        );
        update(
            &["alpha", "bravo", "charlie"],
            &["alpha", "bravo", "delta"],
            vec![Change::Update((2, "delta"))],
            &diff_diff,
        );
    }

    #[test]
    fn lcs_update() {
        update(&[1], &[2], vec![Change::Update((0, 2))], &lcs_diff);
        update(&[1, 2], &[1, 3], vec![Change::Update((1, 3))], &lcs_diff);
        update(
            &[1, 2, 3],
            &[1, 2, 4],
            vec![Change::Update((2, 4))],
            &lcs_diff,
        );
        update(
            &["alpha"],
            &["bravo"],
            vec![Change::Update((0, "bravo"))],
            &lcs_diff,
        );
        update(
            &["alpha", "bravo"],
            &["alpha", "charlie"],
            vec![Change::Update((1, "charlie"))],
            &lcs_diff,
        );
        update(
            &["alpha", "bravo", "charlie"],
            &["alpha", "bravo", "delta"],
            vec![Change::Update((2, "delta"))],
            &lcs_diff,
        );
    }

    #[test]
    fn wu_update() {
        update(&[1], &[2], vec![Change::Update((0, 2))], &wu_diff);
        update(&[1, 2], &[1, 3], vec![Change::Update((1, 3))], &wu_diff);
        update(
            &[1, 2, 3],
            &[1, 2, 4],
            vec![Change::Update((2, 4))],
            &wu_diff,
        );
        update(
            &["alpha"],
            &["bravo"],
            vec![Change::Update((0, "bravo"))],
            &wu_diff,
        );
        update(
            &["alpha", "bravo"],
            &["alpha", "charlie"],
            vec![Change::Update((1, "charlie"))],
            &wu_diff,
        );
        update(
            &["alpha", "bravo", "charlie"],
            &["alpha", "bravo", "delta"],
            vec![Change::Update((2, "delta"))],
            &wu_diff,
        );
    }
}

use std::fmt::Debug;

/**
Process an insert.

- Upgrade `Change::Remove(n), Change::Insert((n, item))` to `Change::Update((n, item))`.
*/
pub fn insert<T: PartialEq + Clone + Debug>(n: usize, item: &T, changes: &mut Vec<Change<T>>) {
    if let Some(prev_change) = changes.pop() {
        if let Change::Remove(prev_n) = prev_change
            && n == prev_n
        {
            changes.push(Change::Update((n, (*item).clone())));
            return;
        }
        changes.push(prev_change);
    }
    changes.push(Change::Insert((n, (*item).clone())));
}

/*
Process a remove.

- Upgrade `Change::Insert((n, item)), Change::Remove(n+1)` to `Change::Update((n, item))`.
*/
pub fn remove<T: PartialEq + Clone + Debug>(n: usize, changes: &mut Vec<Change<T>>) {
    if let Some(prev_change) = changes.pop() {
        if let Change::Insert((prev_n, ref item)) = prev_change
            && n == prev_n + 1
        {
            changes.push(Change::Update((prev_n, item.clone())));
            return;
        }
        changes.push(prev_change);
    }
    changes.push(Change::Remove(n));
}

/**
Abstraction for [`diff::Result`], [`lcs_diff::DiffResult`], and [`wu_diff::DiffResult`] that
excludes a variant for common sequence, stores a clone of inserted items, and indices relate
iteratively to `a`.

[`diff::Result`]: https://docs.rs/diff/latest/diff/enum.Result.html
[`lcs_diff::DiffResult`]: https://docs.rs/lcs-diff/latest/lcs_diff/enum.DiffResult.html
[`wu_diff::DiffResult`]: https://docs.rs/wu-diff/latest/wu_diff/enum.DiffResult.html
*/
#[derive(Debug, Clone, PartialEq)]
pub enum Change<T: PartialEq + Clone + Debug> {
    Remove(usize),
    Insert((usize, T)),
    Update((usize, T)),
}

/**
Convert a slice of [`diff::Result`] into a [`Vec<Change>`].

Note that unlike [`wu_changes`], `b` is not needed to clone inserted items because they are included
in the [`diff::Result`].

[`diff::Result`]: https://docs.rs/diff/latest/diff/enum.Result.html
*/
#[must_use]
pub fn diff_changes<T: PartialEq + Clone + Debug>(d: &[diff::Result<&T>]) -> Vec<Change<T>> {
    let mut changes = vec![];
    let mut removed = 0;
    for (i, j) in d.iter().enumerate() {
        let n = i - removed;
        match j {
            diff::Result::Left(_) => {
                remove(n, &mut changes);
                removed += 1;
            }
            diff::Result::Right(r) => {
                insert(n, *r, &mut changes);
            }
            diff::Result::Both(..) => {}
        }
    }
    changes
}

/**
Calculate the diff between `a` and `b` via [`diff::slice`] and convert to a [`Vec<Change>`].

[`diff::slice`]: https://docs.rs/diff/latest/diff/fn.diff.html
*/
pub fn diff_diff<T: PartialEq + Clone + Debug>(a: &[T], b: &[T]) -> Vec<Change<T>> {
    diff_changes(&diff::slice(a, b))
}

/**
Convert a slice of [`lcs_diff::DiffResult`] into a [`Vec<Change>`].

Note that unlike [`wu_changes`], `b` is not needed to clone inserted items because they are included
in the [`lcs_diff::DiffResult`].

[`lcs_diff::DiffResult`]: https://docs.rs/lcs-diff/latest/lcs_diff/enum.DiffResult.html

# Panics

Panics if not able to resolve the old index of a removed item or the new index of an added item
*/
pub fn lcs_changes<T: PartialEq + Clone + Debug>(d: &[lcs_diff::DiffResult<T>]) -> Vec<Change<T>> {
    let mut changes = vec![];
    let mut removed = 0;
    let mut added = 0;
    for i in d {
        match i {
            lcs_diff::DiffResult::Removed(r) => {
                let n = r.old_index.unwrap() + added - removed;
                remove(n, &mut changes);
                removed += 1;
            }
            lcs_diff::DiffResult::Added(r) => {
                let n = r.new_index.unwrap();
                insert(n, &r.data, &mut changes);
                added += 1;
            }
            lcs_diff::DiffResult::Common(_) => {}
        }
    }
    changes
}

/**
Calculate the diff between `a` and `b` via [`lcs_diff::diff`] and convert to a [`Vec<Change>`].

[`lcs_diff::diff`]: https://docs.rs/lcs-diff/latest/lcs_diff/fn.diff.html
*/
pub fn lcs_diff<T: PartialEq + Clone + Debug>(a: &[T], b: &[T]) -> Vec<Change<T>> {
    lcs_changes(lcs_diff::diff(a, b).as_slice())
}

/**
Convert a slice of [`wu_diff::DiffResult`] into a [`Vec<Change>`].

Note that unlike [`lcs_changes()`], `b` is needed to clone inserted items because they are not
included in the [`wu_diff::DiffResult`].

[`wu_diff::DiffResult`]: https://docs.rs/wu-diff/latest/wu_diff/enum.DiffResult.html

# Panics

Panics if not able to resolve the old index of a removed item or the new index of an added item
*/
pub fn wu_changes<T: PartialEq + Clone + Debug>(
    d: &[wu_diff::DiffResult],
    b: &[T],
) -> Vec<Change<T>> {
    let mut changes = vec![];
    let mut removed = 0;
    let mut added = 0;
    for i in d {
        match i {
            wu_diff::DiffResult::Removed(r) => {
                let n = r.old_index.unwrap() + added - removed;
                remove(n, &mut changes);
                removed += 1;
            }
            wu_diff::DiffResult::Added(r) => {
                let n = r.new_index.unwrap();
                insert(n, &b[n], &mut changes);
                added += 1;
            }
            wu_diff::DiffResult::Common(_) => {}
        }
    }
    changes
}

/**
Calculate the diff between `a` and `b` via [`wu_diff::diff`] and convert to a [`Vec<Change>`].

[`wu_diff::diff`]: https://docs.rs/wu-diff/latest/wu_diff/fn.diff.html
*/
pub fn wu_diff<T: PartialEq + Clone + Debug>(a: &[T], b: &[T]) -> Vec<Change<T>> {
    wu_changes(&wu_diff::diff(a, b), b)
}

/// Reproduce `b` from the `a` slice and [`Vec<Change>`].
pub fn patch<T: PartialEq + Clone + Debug>(a: &[T], changes: &[Change<T>]) -> Vec<T> {
    let mut a = a.to_vec();
    for i in changes {
        match i {
            Change::Remove(n) => {
                a.remove(*n);
            }
            Change::Insert((n, item)) => {
                a.insert(*n, item.clone());
            }
            Change::Update((n, item)) => {
                a.remove(*n);
                a.insert(*n, item.clone());
            }
        }
    }
    a
}