wgdiff 0.4.3

Implementation of LCS-based diff algorithm
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
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
//! # WGSOFT Diff Library
//!
//! This crate provides implementation of a LCS-based difference algorithm,
//! optimized for using in diff-like utilities.
//!
//! # Get Started
//!
//! This crate uses traits to implement its functionality. To get started,
//! read the documentation of following traits:
//!
//! * [`Lcs`]
//! * [`Diff`]
//! * [`Patch`]
//! * [`Patched`]
//!
//! These traits are sealed and are implemented only for slices and [`Vec`]s.
//!
//! [`Lcs`]: Lcs
//! [`Diff`]: Diff
//! [`Patch`]: Patch
//! [`Patched`]: Patched
//! [`Vec`]: Vec

use std::{cmp, ops::Range};

use self::private::Sealed;

/// An operation of deletion of a range of elements from a slice.
pub type Deletion = Range<usize>;

/// An operation of insertion a slice of elements into a slice.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Insertion<'a, T> {
    /// Position to insert into.
    pub start: usize,
    /// Data to be inserted.
    pub data: &'a [T],
}

impl<'a, T> Insertion<'a, T> {
    /// Constructs a new [`Insertion`] from insertion position and data to be
    /// inserted.
    ///
    /// [`Insertion`]: Insertion
    pub fn new(start: usize, data: &'a [T]) -> Self {
        Insertion { start, data }
    }

    /// Convenience method that constructs an owned version of `self`.
    ///
    /// [`Insertion`]: Insertion
    pub fn to_owned(&self) -> OwnedInsertion<T>
    where
        T: Clone,
    {
        self.into()
    }
}

impl<'a, T> From<&'a OwnedInsertion<T>> for Insertion<'a, T> {
    fn from(owned_insertion: &'a OwnedInsertion<T>) -> Self {
        Insertion::new(owned_insertion.start, &owned_insertion.data)
    }
}

/// Owned version of [`Insertion`].
///
/// This `struct` cannot be used in [`patch`] method.
///
/// [`Insertion`]: Insertion
/// [`patch`]: Patch::patch
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct OwnedInsertion<T> {
    /// Position to insert into.
    pub start: usize,
    /// Data to be inserted.
    pub data: Vec<T>,
}

impl<T> OwnedInsertion<T> {
    /// Constructs a new [`OwnedInsertion`] from insertion position and data to
    /// be inserted.
    ///
    /// [`OwnedInsertion`]: OwnedInsertion
    pub fn new(start: usize, data: Vec<T>) -> Self {
        OwnedInsertion { start, data }
    }

    /// Convenience method that constructs a borrowed version of `self`.
    ///
    /// [`Insertion`]: Insertion
    /// [`patch`]: Patch::patch
    pub fn borrow(&self) -> Insertion<T> {
        self.into()
    }
}

impl<T: Clone> From<&Insertion<'_, T>> for OwnedInsertion<T> {
    fn from(insertion: &Insertion<T>) -> Self {
        OwnedInsertion::new(insertion.start, insertion.data.to_vec())
    }
}

/// Description of the difference between two slices.
///
/// This `struct` is the return type of [`diff`] method and can be used in
/// [`patch`] method as well.
///
/// [`diff`]: Diff::diff
/// [`patch`]: Patch::patch
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Difference<'a, T> {
    /// All operations of deletions from a slice.
    pub deletions: Vec<Deletion>,
    /// All operations of insertions into a slice.
    pub insertions: Vec<Insertion<'a, T>>,
}

impl<'a, T> Difference<'a, T> {
    /// Constructs a new [`Difference`] that represents no difference between
    /// slices.
    ///
    /// [`Difference`]: Difference
    pub fn empty() -> Self {
        Difference::new(Vec::new(), Vec::new())
    }

    /// Contructs a new [`Difference`] from [`Deletion`]s and [`Insertion`]s.
    ///
    /// [`Difference`]: Difference
    /// [`Deletion`]: Deletion
    /// [`Insertion`]: Insertion
    pub fn new(
        deletions: Vec<Deletion>,
        insertions: Vec<Insertion<'a, T>>,
    ) -> Self {
        Difference { deletions, insertions }
    }

    /// Convenience method that constructs [`Difference`] from [`Deletion`]s
    /// only.
    ///
    /// [`Difference`]: Difference
    /// [`Deletion`]: Deletion
    pub fn from_deletions(deletions: Vec<Deletion>) -> Self {
        deletions.into()
    }

    /// Convenience method that constructs [`Difference`] from [`Insertion`]s
    /// only.
    ///
    /// [`Difference`]: Difference
    /// [`Insertion`]: Insertion
    pub fn from_insertions(insertions: Vec<Insertion<'a, T>>) -> Self {
        insertions.into()
    }

    /// Convenience method that constructs an owned version of `self`.
    pub fn to_owned(&self) -> OwnedDifference<T>
    where
        T: Clone,
    {
        self.into()
    }
}

impl<T> From<Vec<Deletion>> for Difference<'_, T> {
    fn from(deletions: Vec<Deletion>) -> Self {
        Difference { deletions, insertions: Vec::new() }
    }
}

impl<'a, T> From<Vec<Insertion<'a, T>>> for Difference<'a, T> {
    fn from(insertions: Vec<Insertion<'a, T>>) -> Self {
        Difference { deletions: Vec::new(), insertions }
    }
}

impl<'a, T> From<&'a OwnedDifference<T>> for Difference<'a, T> {
    fn from(owned_difference: &'a OwnedDifference<T>) -> Self {
        Difference::new(
            owned_difference.deletions.clone(),
            owned_difference.insertions.iter().map(Into::into).collect(),
        )
    }
}

/// Owned version of [`Difference`].
///
/// This `struct` cannot be used in [`patch`] method.
///
/// [`Difference`]: Difference
/// [`patch`]: Patch::patch
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct OwnedDifference<T> {
    /// All operations of deletions from a slice.
    pub deletions: Vec<Deletion>,
    /// All operations of insertion into a slice.
    pub insertions: Vec<OwnedInsertion<T>>,
}

impl<T> OwnedDifference<T> {
    /// Constructs a new [`OwnedDifference`] that represents no difference
    /// between slices.
    ///
    /// [`OwnedDifference`]: OwnedDifference
    pub fn empty() -> Self {
        OwnedDifference::new(Vec::new(), Vec::new())
    }

    /// Constructs a new [`OwnedDifference`] from [`Deletion`]s and
    /// [`OwnedInsertion`]s.
    ///
    /// [`OwnedDifference`]: OwnedDifference
    /// [`Deletion`]: Deletion
    /// [`OwnedInsertion`]: OwnedInsertion
    pub fn new(
        deletions: Vec<Deletion>,
        insertions: Vec<OwnedInsertion<T>>,
    ) -> Self {
        OwnedDifference { deletions, insertions }
    }

    /// Convenience method that constructs a new [`OwnedDifference`] from
    /// [`Deletion`]s only.
    ///
    /// [`OwnedDifference`]: OwnedDifference
    /// [`Deletion`]: Deletion
    pub fn from_deletions(deletions: Vec<Deletion>) -> Self {
        deletions.into()
    }

    /// Convenience method that constructs a new [`OwnedDifference`] from
    /// [`OwnedInsertion`]s only.
    ///
    /// [`OwnedDifference`]: OwnedDifference
    /// [`OwnedInsertion`]: OwnedInsertion
    pub fn from_insertions(insertions: Vec<OwnedInsertion<T>>) -> Self {
        insertions.into()
    }

    /// Convenience method that constructs a borrowed version of `self`.
    pub fn borrow(&self) -> Difference<T> {
        self.into()
    }
}

impl<T> From<Vec<Deletion>> for OwnedDifference<T> {
    fn from(deletions: Vec<Deletion>) -> Self {
        OwnedDifference { deletions, insertions: Vec::new() }
    }
}

impl<T> From<Vec<OwnedInsertion<T>>> for OwnedDifference<T> {
    fn from(insertions: Vec<OwnedInsertion<T>>) -> Self {
        OwnedDifference { deletions: Vec::new(), insertions }
    }
}

impl<T: Clone> From<&Difference<'_, T>> for OwnedDifference<T> {
    fn from(difference: &Difference<T>) -> Self {
        OwnedDifference::new(
            difference.deletions.clone(),
            difference.insertions.iter().map(Into::into).collect(),
        )
    }
}

impl<T> Sealed for [T] {}

impl<T> Sealed for Vec<T> {}

/// Trait that contains a method for computing Largest Common Subsequence of two
/// slices.
pub trait Lcs: Sealed {
    /// Calculates the LCS of two slices.
    ///
    /// The [`Vec`]s that this method returns contain indices of elements in
    /// the slices that are common between them. The left value in the tuple
    /// corresponds to `self` and the right value corresponds to `other`.
    fn lcs(&self, other: &Self) -> (Vec<usize>, Vec<usize>);
}

impl<T: Eq> Lcs for [T] {
    fn lcs(&self, other: &Self) -> (Vec<usize>, Vec<usize>) {
        let mut lengths = vec![vec![0; other.len() + 1]; self.len() + 1];

        for (index_self, value_self) in self.iter().enumerate().rev() {
            for (index_other, value_other) in other.iter().enumerate().rev() {
                lengths[index_self][index_other] = if value_self == value_other
                {
                    lengths[index_self + 1][index_other + 1] + 1
                } else {
                    cmp::max(
                        lengths[index_self + 1][index_other],
                        lengths[index_self][index_other + 1],
                    )
                };
            }
        }

        let mut result_self = Vec::new();
        let mut result_other = Vec::new();
        let mut index_self = 0;
        let mut index_other = 0;

        while lengths[index_self][index_other] > 0 {
            if self[index_self] == other[index_other] {
                result_self.push(index_self);
                result_other.push(index_other);

                index_self += 1;
                index_other += 1;
            } else if lengths[index_self + 1][index_other]
                > lengths[index_self][index_other + 1]
            {
                index_self += 1;
            } else {
                index_other += 1;
            }
        }

        (result_self, result_other)
    }
}

impl<T: Eq> Lcs for Vec<T> {
    fn lcs(&self, other: &Self) -> (Vec<usize>, Vec<usize>) {
        (&self[..]).lcs(other)
    }
}

/// Trait that contains a method for computing the LCS based difference of two
/// slices.
pub trait Diff<T>: Lcs {
    /// Calculates the LCS based difference of two slices.
    ///
    /// `self` is assumed to be the new slice, and `old` is assumed to be the
    /// old slice, so in the return value changes are meant to be applied to
    /// `old`, giving `self` in the result.
    fn diff(&self, old: &Self) -> Difference<T>;
}

impl<T: Eq> Diff<T> for [T] {
    fn diff(&self, old: &Self) -> Difference<T> {
        let (lcs_old, lcs_self) = old.lcs(self);

        let mut result = Difference::empty();

        for index in
            (0..old.len()).filter(|index| lcs_old.binary_search(index).is_err())
        {
            match result.deletions.last_mut() {
                Some(Deletion { end, .. }) if index == *end => *end += 1,
                _ => result.deletions.push(index..index + 1),
            }
        }

        for index in (0..self.len())
            .filter(|index| lcs_self.binary_search(index).is_err())
        {
            match result.insertions.last_mut() {
                Some(Insertion { start, data })
                    if index == *start + data.len() =>
                {
                    *data = &self[*start..=index];
                }
                _ => result
                    .insertions
                    .push(Insertion::new(index, &self[index..=index])),
            }
        }

        result
    }
}

impl<T: Eq> Diff<T> for Vec<T> {
    fn diff(&self, old: &Self) -> Difference<T> {
        (&self[..]).diff(old)
    }
}

/// Trait that contains a method for modifying data according to previously
/// obtained [`Difference`].
///
/// [`Difference`]: Difference
pub trait Patch<T>: Diff<T> {
    /// Modifies the data according to the changes listed in `diff`.
    fn patch(&mut self, diff: Difference<T>);
}

impl<T: Eq + Clone> Patch<T> for Vec<T> {
    fn patch(&mut self, diff: Difference<T>) {
        let Difference { deletions, insertions } = diff;

        for deletion in deletions.into_iter().rev() {
            self.drain(deletion);
        }

        for Insertion { start, data } in insertions {
            self.splice(start..start, data.iter().map(Clone::clone));
        }
    }
}

/// Convenience trait that contains a method for constructing new data with
/// changes from previously obtained [`Difference`] applied.
///
/// [`Difference`]: Difference
pub trait Patched<T>: Diff<T> {
    /// Returns a modified version of `self` according to changes listed in
    /// `diff`.
    fn patched(&self, diff: Difference<T>) -> Vec<T>;
}

impl<T: Eq + Clone> Patched<T> for [T] {
    fn patched(&self, diff: Difference<T>) -> Vec<T> {
        let mut vec = self.to_vec();
        vec.patch(diff);
        vec
    }
}

impl<T: Eq + Clone> Patched<T> for Vec<T> {
    fn patched(&self, diff: Difference<T>) -> Vec<T> {
        (&self[..]).patched(diff)
    }
}

mod private {
    pub trait Sealed {}
}

#[cfg(test)]
mod tests {
    use super::{Diff, Difference, Insertion, Lcs, Patched};

    #[test]
    fn lcs() {
        let (left_lcs, right_lcs) = b"BANANA".lcs(b"ATANA");
        assert_eq!(left_lcs, [1, 3, 4, 5]);
        assert_eq!(right_lcs, [0, 2, 3, 4]);

        let (left_lcs, right_lcs) = b"abc".lcs(b"ABC");
        assert_eq!(left_lcs, []);
        assert_eq!(right_lcs, []);

        let (left_lcs, right_lcs) = b"ABC".lcs(b"ABC");
        assert_eq!(left_lcs, [0, 1, 2]);
        assert_eq!(right_lcs, [0, 1, 2]);

        let (left_lcs, right_lcs) = b"ABC".lcs(b"");
        assert_eq!(left_lcs, []);
        assert_eq!(right_lcs, []);

        let (left_lcs, right_lcs) = b"".lcs(b"");
        assert_eq!(left_lcs, []);
        assert_eq!(right_lcs, []);
    }

    #[test]
    fn diff() {
        assert_eq!(
            b"ATANA".diff(b"BANANA"),
            Difference::new(vec![0..1, 2..3], vec![Insertion::new(1, b"T")],)
        );
        assert_eq!(
            b"2345".diff(b"012389"),
            Difference::new(vec![0..2, 4..6], vec![Insertion::new(2, b"45")],)
        );
        assert_eq!(
            b"72345".diff(b"012389"),
            Difference::new(
                vec![0..2, 4..6],
                vec![Insertion::new(0, b"7"), Insertion::new(3, b"45")],
            )
        );
    }

    #[test]
    fn patch() {
        let old = b"BANANA";
        let new = b"ATANA";
        assert_eq!(old.patched(new.diff(old)), new);

        let old = b"012389";
        let new = b"2345";
        assert_eq!(old.patched(new.diff(old)), new);

        let old = b"012389";
        let new = b"72345";
        assert_eq!(old.patched(new.diff(old)), new);
    }
}