deltapatcher 0.2.1

Compute, aggregate, and patch typed deltas between states with timelines, caching, and efficient bidirectional seeking.
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
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
use std::collections::{BTreeMap, VecDeque};

#[cfg(feature = "macros")]
pub use deltapatcher_macros::Diff;

/// Trait for types that can compute the difference (delta)
/// relative to another state of the same type.
///
/// `Diff` represents the generator side of diff patching.
/// Calling `b.diff(&a)` calculates the delta needed to transform `a` into `b`.
///
/// The delta type `D` is **not** required to implement [`Delta`]. `Diff` and
/// [`Patch`] are general-purpose, auxiliary traits: a delta type that only
/// needs to be produced and applied (for example, a single-use-case delta used
/// internally) can implement them without also supporting aggregation. Delta
/// types that implement [`Delta`] are the "complete" deltas that can be used by
/// downstream utilities which need to compose changes.
///
/// # Contract
///
/// **Round-Trip Invariant**: If a type `T` implements both [`Diff<D>`] and [`Patch<D>`], the following identity
/// should hold for any states `a` and `b`:
///
/// ```rust,ignore
/// let mut state = a.clone();
/// let delta = b.diff(&a);
/// state.patch(&delta);
/// assert_eq!(state, b);
/// ```
///
/// In order to help enforce this invariant, it is required that all types capable
/// of producing a delta (i.e. types implementing [`Diff`]) must also be capable of
/// consuming the same type of delta (via [`Patch`]).
///
/// # Examples
///
/// ```rust
/// use deltapatcher::{Diff, Patch, delta::ArithmeticDelta};
///
/// let start = 10i32;
/// let target = 25i32;
/// let delta = target.diff(&start);
/// assert_eq!(delta, ArithmeticDelta(15));
/// ```
pub trait Diff<D>: Patch<D> {
    /// Computes and returns the delta that transforms `initial` into `self`.
    fn diff(&self, initial: &Self) -> D;
}

/// Trait for types that can be updated in-place by applying a delta.
///
/// `Patch` represents the consumption side of differential patching. A type
/// implementing [`Patch<D>`] can mutate its state using a delta `D`, without
/// requiring the capability to compute diffs itself.
///
/// The delta type `D` is **not** required to implement [`Delta`]; see the
/// [`Diff`] docs for the rationale.
///
/// # Examples
///
/// ```rust
/// use deltapatcher::{Patch, delta::ArithmeticDelta};
///
/// let mut value = 10i32;
/// value.patch(&ArithmeticDelta(5));
/// assert_eq!(value, 15);
/// ```
pub trait Patch<D> {
    /// Apply `delta` to `self` in place, advancing it from its current state
    /// to a new state along the delta.
    ///
    /// # Contract
    /// **Round-Trip Invariant**: For a given call to `patch(&mut self, delta)`, if the delta parameter was
    /// generated by [`diff`][Diff::diff] with `self` as the initial state, then the resulting value of `self`
    /// after the call to [`patch`][Self::patch] must be equivalent to the final state passed to [`diff`][Diff::diff].
    /// See [`Diff`] docs for more info.
    ///
    /// # Arguments
    ///
    /// * `delta` — The delta between states.
    ///
    /// # Example
    ///
    /// ```rust
    /// use deltapatcher::delta::{Diff, Patch};
    ///
    /// let before = vec![1u32, 2, 3];
    /// let after  = vec![1u32, 2, 3, 4, 5];
    ///
    /// let delta = after.diff(&before);
    ///
    /// let mut state = before.clone();
    /// state.patch(&delta);
    /// assert_eq!(state, after);
    /// ```
    fn patch(&mut self, delta: &D);
}

/// A value that encodes the change between two states and can be composed
/// with other deltas of the same type.
///
/// A delta is always expressed relative to the state *immediately before* it
/// is applied. Composing two deltas with [`aggregate`][Delta::aggregate]
/// produces a single delta that skips the intermediate state entirely —
/// useful for compressing a sequence of changes before sending them over the
/// network or storing them in a timeline.
///
/// `Delta` is deliberately independent of [`Diff`] and [`Patch`]: those traits
/// work with any delta type, whether or not it supports aggregation. Implement
/// `Delta` only for delta types that should be fully composable and usable by
/// downstream utilities (such as timelines) that need to aggregate changes.
///
/// # Contract
///
/// Aggregation must be **associative**: aggregating `(A→B)` with `(B→C)` and
/// then with `(C→D)` must produce the same result as aggregating `(A→B)` with
/// the pre-aggregated `(B→D)`.
///
/// # Implementing `Delta`
///
/// You typically pair `Delta` with [`Diff`] and [`Patch`] impls on the state
/// type, but this is not required. The only required method is
/// [`aggregate`][Delta::aggregate]; [`aggregate_owned`][Delta::aggregate_owned]
/// has a default implementation that simply borrows its argument, but you
/// should override it whenever moving the data is cheaper than cloning.
///
/// ```rust
/// use deltapatcher::delta::Delta;
///
/// /// A delta for a simple counter: just the signed difference.
/// #[derive(Clone, Copy)]
/// struct CounterDelta(i64);
///
/// impl Delta for CounterDelta {
///     fn aggregate(&mut self, next: &Self) {
///         self.0 += next.0;
///     }
/// }
/// ```
///
/// # Example: composing deltas to skip an intermediate state
///
/// ```rust
/// use deltapatcher::delta::{Delta, Patch, Diff};
///
/// let a = vec![1i32, 2, 3];
/// let b = vec![1i32, 9, 3];     // A → B
/// let c = vec![1i32, 9, 3, 4]; // B → C
///
/// let mut a_to_b = b.diff(&a);
/// let     b_to_c = c.diff(&b);
///
/// // Compose into a single A → C delta — `b` is never needed again.
/// a_to_b.aggregate_owned(b_to_c);
///
/// let mut result = a.clone();
/// result.patch(&a_to_b);
/// assert_eq!(result, c);
/// ```
///
/// # See also
///
/// - [`Diff`] — the trait for types that *produce* deltas.
/// - [`Patch`] — the trait for types that *consume* deltas.
/// - [`SliceDelta`] — built-in delta for [`Vec<T>`], slices, and arrays.
/// - [`ArithmeticDelta`] — built-in delta for integer primitives.
pub trait Delta {
    /// Compose `next` on top of `self` so that applying the result to the
    /// state *before* `self` transitions it all the way to the state *after*
    /// `next`, without materializing the intermediate state.
    ///
    /// After this call `self` represents the aggregated `A → C` delta, where
    /// `self` was originally `A → B` and `next` is `B → C`.
    ///
    /// Prefer [`aggregate_owned`][Delta::aggregate_owned] in hot paths where
    /// you already own `next` and the implementation can avoid a clone.
    fn aggregate(&mut self, next: &Self);

    /// Compose `next` on top of `self` by value.
    ///
    /// This is the preferred hot-path alternative to
    /// [`aggregate`][Delta::aggregate] when the caller already owns `next`,
    /// because implementations can move its internal data rather than cloning
    /// it. The default implementation simply delegates to `aggregate`, so
    /// override this whenever moving is cheaper.
    ///
    /// # Example
    ///
    /// ```rust
    /// use deltapatcher::delta::{Delta, Patch, Diff};
    ///
    /// let a = vec![1u8, 2, 3];
    /// let b = vec![1u8, 5, 3];
    /// let c = vec![1u8, 5, 7];
    ///
    /// let mut d1 = b.diff(&a);
    /// let     d2 = c.diff(&b); // owned — no extra clone needed
    /// d1.aggregate_owned(d2);
    ///
    /// let mut result = a.clone();
    /// result.patch(&d1);
    /// assert_eq!(result, c);
    /// ```
    fn aggregate_owned(&mut self, next: Self)
    where
        Self: Sized
    {
        self.aggregate(&next);
    }
}

// TODO reversable delta trait

/// A delta which represents item changes in a vector or slice
// TODO create a variant of [`SliceDelta`] for types like structs which may contain
// large enough items to diff rather than cloning.
#[derive(Debug, Clone)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct SliceDelta<T> {
    /// The non-overlapping splices expressed in
    /// the coordinate system of the vector before
    /// the delta is applied.
    entries: BTreeMap<u32, SliceDeltaEntry<T>>,
}

impl<T> Default for SliceDelta<T> {
    fn default() -> Self {
        Self {
            entries: BTreeMap::new(),
        }
    }
}

impl<T> SliceDelta<T> {
    pub fn new() -> Self {
        Self::default()
    }

    /// Insert `next` into the entry map, merging it with any entries whose
    /// ranges it touches or overlaps.
    ///
    /// `next` must already be expressed in the same coordinate space as the
    /// rest of `entries` (i.e. positions in the pre-delta vector) — this is
    /// *not* the method that translates a "next" [`Delta`]'s B-space
    /// coordinates into A-space; that translation happens in
    /// [`Delta::aggregate`].
    ///
    /// Entries that merely *touch* `next` (no gap between them) are
    /// concatenated, which is lossless. Entries that genuinely *overlap*
    /// `next`'s range are dropped in favor of `next`, since a `Vec<T>` of
    /// added items carries no addressable sub-range information to resolve
    /// a partial conflict — `next` is treated as authoritative for any
    /// range it claims.
    pub fn aggregate_entry(&mut self, mut next: SliceDeltaEntry<T>) {
        // at most one existing entry can touch/overlap `next` from the left
        // (entries are non-overlapping, so the immediate predecessor is the
        // only candidate).
        let lower = self
            .entries
            .range(..next.start_index)
            .next_back()
            .filter(|(_, e)| e.remove_end() >= next.start_index)
            .map(|(&k, _)| k);

        if let Some(k) = lower {
            let prev = self.entries.remove(&k).unwrap();
            next = merge_two(prev, next);
        }

        // any number of entries can touch/overlap from the right, so keep
        // absorbing until nothing more qualifies.
        loop {
            let upper = self
                .entries
                .range(next.start_index..)
                .next()
                .filter(|(_, e)| e.start_index <= next.remove_end())
                .map(|(&k, _)| k);

            match upper {
                Some(k) => {
                    let other = self.entries.remove(&k).unwrap();
                    next = merge_two(next, other);
                }
                None => break,
            }
        }

        self.entries.insert(next.start_index, next);
    }
}

/// Merges two entries known to be touching or overlapping, with `a` sorted
/// before `b` (`a.start_index <= b.start_index`). See [`SliceDelta::aggregate_entry`]
/// for the semantics when they genuinely overlap.
fn merge_two<T>(a: SliceDeltaEntry<T>, b: SliceDeltaEntry<T>) -> SliceDeltaEntry<T> {
    debug_assert!(a.start_index <= b.start_index);
    let start = a.start_index;
    let remove_end = a.remove_end().max(b.remove_end());
    let mut add = a.add;
    add.extend(b.add);
    SliceDeltaEntry {
        start_index: start,
        remove: remove_end - start,
        add,
    }
}

/// One piece of the vector produced by a `SliceDelta`, used only internally
/// to compose two deltas. Either a run of items carried over unchanged from
/// the pre-delta vector (identified by its range there), or a run of items
/// that were literally inserted and therefore don't exist in the pre-delta
/// vector at all.
enum Segment<T> {
    /// `a_end == None` means "extends to the end of the vector" — this lets
    /// us represent the untouched tail without ever knowing the vector's
    /// actual length.
    Unchanged { a_start: u32, a_end: Option<u32> },
    Added(Vec<T>),
}

impl<T> Segment<T> {
    fn len(&self) -> Option<u32> {
        match self {
            Segment::Unchanged { a_start, a_end } => a_end.map(|e| e - a_start),
            Segment::Added(items) => Some(items.len() as u32),
        }
    }
}

/// Discards exactly `want` B-space positions from the front of `segments`,
/// splitting the boundary segment if needed.
fn take_front<T: Clone>(segments: &mut VecDeque<Segment<T>>, mut want: u32) {
    while want > 0 {
        let seg = segments
            .front_mut()
            .expect("next's entries remove more content than is available");
        match seg.len() {
            Some(avail) if avail <= want => {
                want -= avail;
                segments.pop_front();
            }
            _ => {
                match seg {
                    Segment::Unchanged { a_start, .. } => *a_start += want,
                    Segment::Added(items) => {
                        items.drain(0..want as usize);
                    }
                }
                want = 0;
            }
        }
    }
}

/// Moves exactly `want` B-space positions' worth of segments from the front
/// of `segments` onto the back of `output`, splitting the boundary segment
/// if needed.
fn advance_to<T: Clone>(segments: &mut VecDeque<Segment<T>>, output: &mut Vec<Segment<T>>, mut want: u32) {
    while want > 0 {
        let avail = segments
            .front()
            .expect("next's entries start past the end of the aggregated vector")
            .len();
        match avail {
            Some(avail) if avail <= want => {
                want -= avail;
                output.push(segments.pop_front().unwrap());
            }
            _ => {
                let front = segments.front_mut().unwrap();
                match front {
                    Segment::Unchanged { a_start, .. } => {
                        let split = *a_start + want;
                        output.push(Segment::Unchanged {
                            a_start: *a_start,
                            a_end: Some(split),
                        });
                        *a_start = split;
                    }
                    Segment::Added(items) => {
                        let head: Vec<T> = items.drain(0..want as usize).collect();
                        output.push(Segment::Added(head));
                    }
                }
                want = 0;
            }
        }
    }
}

impl<T: Clone> Delta for SliceDelta<T> {
    fn aggregate(&mut self, next: &Self) {
        self.aggregate_owned(next.clone());
    }

    fn aggregate_owned(&mut self, next: Self) {
        // Step 1: express B as segments over self's own (owned) entries.
        let mut segments: VecDeque<Segment<T>> = VecDeque::new();
        let mut cursor_a = 0u32;
        for entry in std::mem::take(&mut self.entries).into_values() {
            if entry.start_index > cursor_a {
                segments.push_back(Segment::Unchanged {
                    a_start: cursor_a,
                    a_end: Some(entry.start_index),
                });
            }
            cursor_a = entry.remove_end();
            if !entry.add.is_empty() {
                segments.push_back(Segment::Added(entry.add)); // moved
            }
        }
        segments.push_back(Segment::Unchanged {
            a_start: cursor_a,
            a_end: None,
        });

        // Step 2: sweep next's (owned) entries across those segments.
        let mut output: Vec<Segment<T>> = Vec::new();
        let mut b_cursor = 0u32;
        for entry in next.entries.into_values() {
            advance_to(&mut segments, &mut output, entry.start_index - b_cursor);
            take_front(&mut segments, entry.remove);
            b_cursor = entry.remove_end(); // compute first, while `entry` is intact
            if !entry.add.is_empty() {
                output.push(Segment::Added(entry.add)); // now safe to move
            }
        }
        output.extend(segments);

        // Step 3: translate the merged segment list back into A-space entries.
        let mut new_entries = BTreeMap::new();
        let mut next_expected_a = 0u32;
        let mut add_buffer: Vec<T> = Vec::new();
        for segment in output {
            match segment {
                Segment::Added(items) => add_buffer.extend(items),
                Segment::Unchanged { a_start, a_end } => {
                    if a_start != next_expected_a || !add_buffer.is_empty() {
                        let entry = SliceDeltaEntry::new(
                            next_expected_a,
                            a_start - next_expected_a,
                            std::mem::take(&mut add_buffer),
                        );
                        new_entries.insert(entry.start_index, entry);
                    }
                    next_expected_a = a_end.unwrap_or(a_start);
                }
            }
        }

        self.entries = new_entries;
    }
}

/// Computes a [`SliceDelta`] representing the changes needed to turn
/// `initial` into `final_`, via LCS-based diffing. Shared between the
/// `Vec<T>` and `[T]` [`Diff`] impls — diffing itself doesn't
/// care whether the result will later be applied to a resizable or
/// fixed-size container; only `patch` differs between them.
fn diff_slices<T: Clone + PartialEq>(initial: &[T], final_: &[T]) -> SliceDelta<T> {
    let n = initial.len();
    let m = final_.len();

    let mut lcs = vec![vec![0u32; m + 1]; n + 1];
    for i in (0..n).rev() {
        for j in (0..m).rev() {
            lcs[i][j] = if initial[i] == final_[j] {
                lcs[i + 1][j + 1] + 1
            } else {
                lcs[i + 1][j].max(lcs[i][j + 1])
            };
        }
    }

    let mut entries = BTreeMap::new();
    let (mut i, mut j) = (0usize, 0usize);
    let mut run_start: Option<usize> = None;
    let mut run_add: Vec<T> = Vec::new();
    let mut run_remove = 0u32;

    macro_rules! flush {
        () => {
            #[allow(unused_assignments)]
            {
                if let Some(start) = run_start.take() {
                    if run_remove != 0 || !run_add.is_empty() {
                        let entry = SliceDeltaEntry::new(
                            start as u32,
                            run_remove,
                            std::mem::take(&mut run_add),
                        );
                        entries.insert(entry.start_index, entry);
                    }
                    run_remove = 0;
                }
            }
        };
    }

    while i < n && j < m {
        if initial[i] == final_[j] {
            flush!();
            i += 1;
            j += 1;
        } else if lcs[i + 1][j] >= lcs[i][j + 1] {
            run_start.get_or_insert(i);
            run_remove += 1;
            i += 1;
        } else {
            run_start.get_or_insert(i);
            run_add.push(final_[j].clone());
            j += 1;
        }
    }
    if i < n {
        run_start.get_or_insert(i);
        run_remove += (n - i) as u32;
    }
    if j < m {
        run_start.get_or_insert(n);
        run_add.extend(final_[j..].iter().cloned());
    }
    flush!();

    SliceDelta { entries }
}

impl<T: Clone + PartialEq> Diff<SliceDelta<T>> for Vec<T> {
    fn diff(&self, initial: &Self) -> SliceDelta<T> {
        diff_slices(initial, self)
    }
}

impl<T: Clone> Patch<SliceDelta<T>> for Vec<T> {
    fn patch(&mut self, delta: &SliceDelta<T>) {
        for entry in delta.entries.values().rev() {
            let start = entry.start_index as usize;
            let end = start + entry.remove as usize;

            self.splice(start..end, entry.add.iter().cloned());
        }
    }
}

impl<T: Clone + PartialEq> Diff<SliceDelta<T>> for [T] {
    fn diff(&self, initial: &Self) -> SliceDelta<T> {
        diff_slices(initial, self)
    }
}

impl<T: Clone + PartialEq> Patch<SliceDelta<T>> for [T] {
    fn patch(&mut self, delta: &SliceDelta<T>) {
        let mut buffer: Vec<T> = Vec::with_capacity(self.len());
        let mut read = 0usize;

        for entry in delta.entries.values() {
            let start = entry.start_index as usize;
            buffer.extend_from_slice(&self[read..start]);
            read = start + entry.remove as usize;
            buffer.extend(entry.add.iter().cloned());
        }

        buffer.extend_from_slice(&self[read..]);

        assert!(
            buffer.len() <= self.len(),
            "patch would increase the length of the slice"
        );

        self[..buffer.len()].clone_from_slice(&buffer);
    }
}

impl<T: Clone + PartialEq, const N: usize> Diff<SliceDelta<T>> for [T; N] {
    fn diff(&self, initial: &Self) -> SliceDelta<T> {
        <[T] as Diff<SliceDelta<T>>>::diff(self, initial)
    }
}

impl<T: Clone + PartialEq, const N: usize> Patch<SliceDelta<T>> for [T; N] {
    fn patch(&mut self, delta: &SliceDelta<T>) {
        <[T]>::patch(self, delta)
    }
}

/// A splicing entry in the delta
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct SliceDeltaEntry<T> {
    /// The start index of the entry within the vec
    start_index: u32,

    /// The number of items removed as a result of the entry
    remove: u32,

    /// The items added as a result of the entry.
    /// When applied, these are added after the others are removed.
    add: Vec<T>,
}

impl<T> SliceDeltaEntry<T> {
    pub fn new(start_index: u32, remove: u32, add: Vec<T>) -> Self {
        assert!(remove != 0 || !add.is_empty());

        Self {
            start_index,
            remove,
            add,
        }
    }

    pub fn insert(start_index: u32, add: Vec<T>) -> Self {
        Self::new(start_index, 0, add)
    }

    pub fn remove(start_index: u32, remove: u32) -> Self {
        Self::new(start_index, remove, Vec::new())
    }

    pub fn replace(start_index: u32, new_values: Vec<T>) -> Self {
        Self::new(start_index, new_values.len() as u32, new_values)
    }

    pub const fn remove_end(&self) -> u32 {
        self.start_index + self.remove
    }

    pub const fn add_len(&self) -> u32 {
        self.add.len() as u32
    }

    pub const fn end_after(&self) -> u32 {
        self.start_index + self.add_len()
    }

    pub const fn delta_len(&self) -> i64 {
        self.add_len() as i64 - self.remove as i64
    }

    pub const fn contains_index(&self, index: u32) -> bool {
        index >= self.start_index && index < self.remove_end()
    }
}

/// A delta defined by addition/subtraction.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct ArithmeticDelta<T: WrappingArithmetic>(pub T);

impl<T> Delta for ArithmeticDelta<T>
where 
    T: WrappingArithmetic,
{
    fn aggregate(&mut self, next: &Self) {
        self.0 = self.0.wrapping_add(next.0);
    }
}

// arithmetic overflow is necessary for some edge cases to work properly
pub trait WrappingArithmetic: Copy {
    fn wrapping_add(self, rhs: Self) -> Self;
    fn wrapping_sub(self, rhs: Self) -> Self;
}

macro_rules! impl_wrapping_arith {
    ($T: ty) => {
        impl WrappingArithmetic for $T {
            fn wrapping_add(self, rhs: $T) -> $T {
                <$T>::wrapping_add(self, rhs)
            }

            fn wrapping_sub(self, rhs: $T) -> $T {
                <$T>::wrapping_sub(self, rhs)
            }
        }
    };
    ($($T: ty),*) => {
        $(impl_wrapping_arith!($T);)*
    };
}

impl_wrapping_arith! {
    u8,
    u16,
    u32,
    u64,
    i8,
    i16,
    i32,
    i64
}

impl<T: WrappingArithmetic> Diff<ArithmeticDelta<Self>> for T
{
    fn diff(&self, initial: &Self) -> ArithmeticDelta<Self> {
        ArithmeticDelta(self.wrapping_sub(*initial))
    }
}

impl<T: WrappingArithmetic> Patch<ArithmeticDelta<Self>> for T
{
    fn patch(&mut self, delta: &ArithmeticDelta<Self>) {
        *self = self.wrapping_add(delta.0);
    }
}

// TODO generic additive (or scalar?) delta for types which don't care about overflows.

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

    // Note: `D` intentionally has no `Delta` bound — `Diff`/`Patch` work with
    // any delta type, including ones that don't support aggregation.
    fn assert_roundtrip<T, D>(initial: T, final_: T)
    where 
        T: Diff<D> + Clone + PartialEq + std::fmt::Debug,
    {
        let delta = final_.diff(&initial);
        let mut applied = initial.clone();
        applied.patch(&delta);
        assert_eq!(applied, final_);
    }

    /// Tests that `Diff`/`Patch` can be implemented for a delta type that
    /// does not implement `Delta` (a "specific-usecase delta").
    mod without_delta {
        use super::*;

        /// A delta that only records whether a `bool` changed. It has no
        /// meaningful `aggregate` implementation, so it does not implement `Delta`.
        #[derive(Debug, Clone, Copy, PartialEq, Eq)]
        struct Flip(bool);

        impl Diff<Flip> for bool {
            fn diff(&self, initial: &Self) -> Flip {
                Flip(self != initial)
            }
        }

        impl Patch<Flip> for bool {
            fn patch(&mut self, delta: &Flip) {
                if delta.0 {
                    *self = !*self;
                }
            }
        }

        #[test]
        fn diff_and_apply() {
            assert_roundtrip::<bool, Flip>(true, false);
            assert_roundtrip::<bool, Flip>(false, true);
            assert_roundtrip::<bool, Flip>(true, true);
            assert_roundtrip::<bool, Flip>(false, false);
        }
    }
    
    mod slice {
        use super::*;

        #[test]
        fn diff_and_apply() {
                    assert_roundtrip(vec![1, 2, 3, 4], vec![1, 5, 3, 6, 4]);
            assert_roundtrip(vec![1, 2, 3], vec![]);
            assert_roundtrip(vec![], vec![1, 2, 3]);
            assert_roundtrip(vec![1, 2, 3], vec![1, 2, 3]);
        }

        #[test]
        fn aggregate_matches_direct_diff() {
            let a = vec![1, 2, 3, 4, 5];
            let b = vec![1, 9, 3, 4, 10, 5];
            let c = vec![9, 3, 11, 4, 10];

                        let mut d1 = b.diff(&a);
            let d2 = c.diff(&b);
            d1.aggregate(&d2);

            let mut applied = a.clone();
            applied.patch(&d1);
            assert_eq!(applied, c);
        }

        #[test]
        fn aggregate_entry_merges_touching_ranges() {
            let mut delta = SliceDelta::<i32>::new();
            delta.aggregate_entry(SliceDeltaEntry::replace(0, vec![1, 2]));
            delta.aggregate_entry(SliceDeltaEntry::replace(2, vec![3]));

            assert_eq!(delta.entries.len(), 1);
            let entry = delta.entries.values().next().unwrap();
            assert_eq!(entry.start_index, 0);
            assert_eq!(entry.add, vec![1, 2, 3]);
        }

        #[test]
        fn slice_patch_same_length() {
                        let initial = [1, 2, 3, 4];
            let final_ = vec![1, 5, 3, 6];
            let delta = final_.diff(&initial.to_vec());

            let mut buf = initial;
            buf.patch(&delta);
            assert_eq!(buf, [1, 5, 3, 6]);
        }

        #[test]
        fn slice_patch_shrink_ok() {
            let initial = [1, 2, 3, 4, 5];
                        let final_ = vec![1, 3, 5];
            let delta = final_.diff(&initial.to_vec());

            let mut buf = initial;
            buf.patch(&delta);
            assert_eq!(&buf[..3], [1, 3, 5]); // trailing elements are stale, not checked
        }

        #[test]
        #[should_panic(expected = "increase the length")]
        fn slice_patch_growth_panics() {
            let initial = [1, 2, 3];
                        let final_ = vec![1, 2, 3, 4];
            let delta = final_.diff(&initial.to_vec());

            let mut buf = initial;
            buf.patch(&delta);
        }

        #[test]
        fn slice_patch_permutation_no_extra_space() {
            let initial: [u8; 10] = [4, 5, 6, 7, 8, 9, 10, 1, 2, 3];
                        let final_ = vec![8, 1, 5, 2, 3, 6, 7, 9, 10, 4];
            let delta = final_.diff(&initial.to_vec());
            let mut buf = initial;
            buf.patch(&delta); // previously panicked with the compaction version
            assert_eq!(buf, [8, 1, 5, 2, 3, 6, 7, 9, 10, 4]);
        }
    }
    
        mod arithmetic {
        use super::*;

        #[test]
        fn diff_and_apply() {
                    assert_roundtrip(5u32, 10u32);
            assert_roundtrip(-1i32, i32::MAX);
            assert_roundtrip(i32::MIN, i32::MAX);
            assert_roundtrip(u8::MAX, u8::MIN);
            // assert_roundtrip(2.34, 6.78);
            // assert_roundtrip(28930.345f64, 28930.345f64);
        }
    }

        /// Tests for `#[derive(Diff)]` on enums.
    #[cfg(feature = "macros")]
    mod derive_enum {
        use super::*;
        use deltapatcher_macros::Diff;
        // The macro emits `deltapatcher::delta::...` paths.  When the tests
        // run inside the `deltapatcher` crate itself, we need the crate to
        // be accessible under that name.
        extern crate self as deltapatcher;

        // ----------------------------------------------------------------
        // Test types
        // ----------------------------------------------------------------

        /// An enum with every kind of variant (named fields, unnamed fields,
        /// and unit) so that one set of tests covers all three code paths.
        #[derive(Diff, Debug, Clone, PartialEq)]
        enum Shape {
            /// Named-field variant.
            Rect {
                #[deltapatcher(delta_ty = ArithmeticDelta<i32>)]
                width: i32,
                #[deltapatcher(delta_ty = ArithmeticDelta<i32>)]
                height: i32,
            },
            /// Unnamed-field (tuple) variant.
            Circle(
                #[deltapatcher(delta_ty = ArithmeticDelta<u32>)]
                u32,
            ),
            /// Unit variant.
            Point,
        }

        // ----------------------------------------------------------------
        // same-variant: diff + patch
        // ----------------------------------------------------------------

        #[test]
        fn same_variant_named_roundtrip() {
            assert_roundtrip(
                Shape::Rect { width: 10, height: 20 },
                Shape::Rect { width: 30, height: 5  },
            );
        }

        #[test]
        fn same_variant_unnamed_roundtrip() {
            assert_roundtrip(Shape::Circle(4), Shape::Circle(100));
        }

        #[test]
        fn same_variant_unit_roundtrip() {
            assert_roundtrip(Shape::Point, Shape::Point);
        }

        // ----------------------------------------------------------------
        // cross-variant: diff produces Replace, patch overwrites
        // ----------------------------------------------------------------

        #[test]
        fn cross_variant_named_to_unnamed_roundtrip() {
            assert_roundtrip(
                Shape::Rect { width: 1, height: 2 },
                Shape::Circle(99),
            );
        }

        #[test]
        fn cross_variant_unnamed_to_unit_roundtrip() {
            assert_roundtrip(Shape::Circle(7), Shape::Point);
        }

        #[test]
        fn cross_variant_unit_to_named_roundtrip() {
            assert_roundtrip(
                Shape::Point,
                Shape::Rect { width: -3, height: 42 },
            );
        }

        // ----------------------------------------------------------------
        // aggregate: same variant on both sides
        // ----------------------------------------------------------------

        #[test]
        fn aggregate_same_variant_matches_direct_diff() {
            let a = Shape::Rect { width: 0,  height: 0  };
            let b = Shape::Rect { width: 10, height: -5 };
            let c = Shape::Rect { width: 3,  height: 20 };

            let mut d_ab = b.diff(&a);
            let     d_bc = c.diff(&b);
            d_ab.aggregate(&d_bc);

            let mut result = a.clone();
            result.patch(&d_ab);
            assert_eq!(result, c);
        }

        // ----------------------------------------------------------------
        // aggregate: first delta is Replace (self already replaced)
        // ----------------------------------------------------------------

        /// A → (Replace B) then B → C should collapse to A → (Replace C).
        #[test]
        fn aggregate_replace_then_same_variant() {
            let a = Shape::Circle(1);
            let b = Shape::Rect { width: 10, height: 20 };
            let c = Shape::Rect { width: 30, height: 5  };

            // d1 is Replace(b) because the variants differ
            let mut d1 = b.diff(&a);
            // d2 is a same-variant named-field delta
            let d2 = c.diff(&b);
            d1.aggregate(&d2);

            let mut result = a.clone();
            result.patch(&d1);
            assert_eq!(result, c);
        }

        // ----------------------------------------------------------------
        // aggregate: second delta is Replace (next replaces everything)
        // ----------------------------------------------------------------

        /// A → B then (Replace C) should collapse to A → (Replace C).
        #[test]
        fn aggregate_same_variant_then_replace() {
            let a = Shape::Rect { width: 0, height: 0 };
            let b = Shape::Rect { width: 5, height: 5 };
            let c = Shape::Circle(42);

            let mut d1 = b.diff(&a);
            let     d2 = c.diff(&b); // Replace(Circle(42))
            d1.aggregate(&d2);

            let mut result = a.clone();
            result.patch(&d1);
            assert_eq!(result, c);
        }

        // ----------------------------------------------------------------
        // aggregate: both deltas are Replace
        // ----------------------------------------------------------------

        #[test]
        fn aggregate_replace_then_replace() {
            let a = Shape::Point;
            let b = Shape::Circle(10);
            let c = Shape::Rect { width: -1, height: -1 };

            let mut d1 = b.diff(&a); // Replace(Circle(10))
            let     d2 = c.diff(&b); // Replace(Rect { .. })
            d1.aggregate(&d2);

            let mut result = a.clone();
            result.patch(&d1);
            assert_eq!(result, c);
        }
    }
}