ftui-core 0.4.0

Terminal lifecycle, capabilities, and event parsing for FrankenTUI.
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
//! Structural diff and patch via datatype-generic representation.
//!
//! Works with any type implementing [`GenericRepr`] by computing diffs on
//! the Sum/Product/Unit encoding and applying patches to transform values.
//!
//! # Example
//!
//! ```
//! use ftui_core::generic_repr::*;
//! use ftui_core::generic_diff::*;
//!
//! #[derive(Clone, Debug, PartialEq)]
//! struct Point { x: f64, y: f64 }
//!
//! impl GenericRepr for Point {
//!     type Repr = Product<f64, Product<f64, Unit>>;
//!     fn into_repr(self) -> Self::Repr {
//!         Product(self.x, Product(self.y, Unit))
//!     }
//!     fn from_repr(repr: Self::Repr) -> Self {
//!         Point { x: repr.0, y: repr.1.0 }
//!     }
//! }
//!
//! let old = Point { x: 1.0, y: 2.0 };
//! let new = Point { x: 1.0, y: 3.0 };
//! let diff = generic_diff(&old, &new);
//! let patched = generic_patch(&old, &diff);
//! assert_eq!(patched, new);
//! assert!(!diff.is_empty());
//! ```

use crate::generic_repr::*;
use std::fmt;

// ── Delta type ──────────────────────────────────────────────────────

/// A change delta: either unchanged or replaced with a new value.
#[derive(Clone, PartialEq, Eq)]
pub enum Delta<T> {
    /// Value is unchanged.
    Same,
    /// Value was replaced.
    Changed(T),
}

impl<T: fmt::Debug> fmt::Debug for Delta<T> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Delta::Same => write!(f, "Same"),
            Delta::Changed(v) => write!(f, "Changed({v:?})"),
        }
    }
}

impl<T> Delta<T> {
    /// Whether this delta represents no change.
    pub fn is_same(&self) -> bool {
        matches!(self, Delta::Same)
    }

    /// Whether this delta represents a change.
    pub fn is_changed(&self) -> bool {
        matches!(self, Delta::Changed(_))
    }
}

// ── Diff trait ──────────────────────────────────────────────────────

/// Compute a structural diff between two values of the same type.
///
/// The diff type `Self::Diff` captures what changed between `old` and `new`.
pub trait Diff: Sized {
    /// The diff representation for this type.
    type Diff: DiffInfo;

    /// Compute the diff from `old` to `new`.
    fn diff(old: &Self, new: &Self) -> Self::Diff;
}

/// Metadata about a diff.
pub trait DiffInfo {
    /// Whether the diff represents no changes (identity patch).
    fn is_empty(&self) -> bool;
    /// Number of changed fields/variants.
    fn change_count(&self) -> usize;
}

// ── Patch trait ─────────────────────────────────────────────────────

/// Apply a diff to transform a value.
pub trait Patch: Diff {
    /// Apply the diff to `old` to produce `new`.
    fn patch(old: &Self, diff: &Self::Diff) -> Self;
}

// ── Leaf impls ──────────────────────────────────────────────────────

/// Blanket leaf-level diff: compare via PartialEq, delta is the new value.
impl<T: Clone + PartialEq> Diff for T
where
    T: LeafDiff,
{
    type Diff = Delta<T>;

    fn diff(old: &Self, new: &Self) -> Delta<T> {
        if old == new {
            Delta::Same
        } else {
            Delta::Changed(new.clone())
        }
    }
}

impl<T: Clone + PartialEq> Patch for T
where
    T: LeafDiff,
{
    fn patch(old: &Self, diff: &Delta<T>) -> Self {
        match diff {
            Delta::Same => old.clone(),
            Delta::Changed(v) => v.clone(),
        }
    }
}

/// Marker trait for types that use leaf-level (PartialEq) diffing.
///
/// Implement this for primitive types and small value types that should
/// be compared atomically rather than structurally.
pub trait LeafDiff {}

// Implement LeafDiff for common primitives
impl LeafDiff for bool {}
impl LeafDiff for u8 {}
impl LeafDiff for u16 {}
impl LeafDiff for u32 {}
impl LeafDiff for u64 {}
impl LeafDiff for u128 {}
impl LeafDiff for usize {}
impl LeafDiff for i8 {}
impl LeafDiff for i16 {}
impl LeafDiff for i32 {}
impl LeafDiff for i64 {}
impl LeafDiff for i128 {}
impl LeafDiff for isize {}
impl LeafDiff for f32 {}
impl LeafDiff for f64 {}
impl LeafDiff for char {}
impl LeafDiff for String {}
impl LeafDiff for &str {}

impl<T> DiffInfo for Delta<T> {
    fn is_empty(&self) -> bool {
        self.is_same()
    }
    fn change_count(&self) -> usize {
        if self.is_changed() { 1 } else { 0 }
    }
}

// ── Product diff ────────────────────────────────────────────────────

/// Diff of a product: diff each component independently.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ProductDiff<HD, TD> {
    pub head: HD,
    pub tail: TD,
}

impl<HD: DiffInfo, TD: DiffInfo> DiffInfo for ProductDiff<HD, TD> {
    fn is_empty(&self) -> bool {
        self.head.is_empty() && self.tail.is_empty()
    }
    fn change_count(&self) -> usize {
        self.head.change_count() + self.tail.change_count()
    }
}

impl<H: Diff, T: Diff> Diff for Product<H, T> {
    type Diff = ProductDiff<H::Diff, T::Diff>;

    fn diff(old: &Self, new: &Self) -> Self::Diff {
        ProductDiff {
            head: H::diff(&old.0, &new.0),
            tail: T::diff(&old.1, &new.1),
        }
    }
}

impl<H: Patch, T: Patch> Patch for Product<H, T> {
    fn patch(old: &Self, diff: &Self::Diff) -> Self {
        Product(H::patch(&old.0, &diff.head), T::patch(&old.1, &diff.tail))
    }
}

// ── Unit diff ───────────────────────────────────────────────────────

/// Diff of a Unit: always empty (nothing to compare).
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct UnitDiff;

impl DiffInfo for UnitDiff {
    fn is_empty(&self) -> bool {
        true
    }
    fn change_count(&self) -> usize {
        0
    }
}

impl Diff for Unit {
    type Diff = UnitDiff;
    fn diff(_old: &Self, _new: &Self) -> UnitDiff {
        UnitDiff
    }
}

impl Patch for Unit {
    fn patch(_old: &Self, _diff: &UnitDiff) -> Self {
        Unit
    }
}

// ── Sum diff ────────────────────────────────────────────────────────

/// Diff of a sum type: either both are the same variant (structural diff)
/// or the variant changed (full replacement).
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum SumDiff<LD, RD, L, R> {
    /// Both values are Left; contains diff of inner values.
    BothLeft(LD),
    /// Both values are Right; contains diff of inner values.
    BothRight(RD),
    /// Variant changed from Left to Right.
    LeftToRight(R),
    /// Variant changed from Right to Left.
    RightToLeft(L),
}

impl<LD: DiffInfo, RD: DiffInfo, L, R> DiffInfo for SumDiff<LD, RD, L, R> {
    fn is_empty(&self) -> bool {
        match self {
            SumDiff::BothLeft(d) => d.is_empty(),
            SumDiff::BothRight(d) => d.is_empty(),
            SumDiff::LeftToRight(_) | SumDiff::RightToLeft(_) => false,
        }
    }
    fn change_count(&self) -> usize {
        match self {
            SumDiff::BothLeft(d) => d.change_count(),
            SumDiff::BothRight(d) => d.change_count(),
            SumDiff::LeftToRight(_) | SumDiff::RightToLeft(_) => 1,
        }
    }
}

impl<L: Diff + Clone, R: Diff + Clone> Diff for Sum<L, R> {
    type Diff = SumDiff<L::Diff, R::Diff, L, R>;

    fn diff(old: &Self, new: &Self) -> Self::Diff {
        match (old, new) {
            (Sum::Left(o), Sum::Left(n)) => SumDiff::BothLeft(L::diff(o, n)),
            (Sum::Right(o), Sum::Right(n)) => SumDiff::BothRight(R::diff(o, n)),
            (Sum::Left(_), Sum::Right(n)) => SumDiff::LeftToRight(n.clone()),
            (Sum::Right(_), Sum::Left(n)) => SumDiff::RightToLeft(n.clone()),
        }
    }
}

impl<L: Patch + Clone, R: Patch + Clone> Patch for Sum<L, R> {
    fn patch(old: &Self, diff: &Self::Diff) -> Self {
        match diff {
            SumDiff::BothLeft(d) => match old {
                Sum::Left(o) => Sum::Left(L::patch(o, d)),
                Sum::Right(_) => unreachable!("BothLeft diff applied to Right"),
            },
            SumDiff::BothRight(d) => match old {
                Sum::Right(o) => Sum::Right(R::patch(o, d)),
                Sum::Left(_) => unreachable!("BothRight diff applied to Left"),
            },
            SumDiff::LeftToRight(v) => Sum::Right(v.clone()),
            SumDiff::RightToLeft(v) => Sum::Left(v.clone()),
        }
    }
}

// ── Field diff ──────────────────────────────────────────────────────

impl<T: Diff> Diff for Field<T> {
    type Diff = T::Diff;

    fn diff(old: &Self, new: &Self) -> T::Diff {
        T::diff(&old.value, &new.value)
    }
}

impl<T: Patch> Patch for Field<T> {
    fn patch(old: &Self, diff: &T::Diff) -> Self {
        Field {
            name: old.name,
            value: T::patch(&old.value, diff),
        }
    }
}

// ── Variant diff ────────────────────────────────────────────────────

impl<T: Diff> Diff for Variant<T> {
    type Diff = T::Diff;

    fn diff(old: &Self, new: &Self) -> T::Diff {
        T::diff(&old.value, &new.value)
    }
}

impl<T: Patch> Patch for Variant<T> {
    fn patch(old: &Self, diff: &T::Diff) -> Self {
        Variant {
            name: old.name,
            value: T::patch(&old.value, diff),
        }
    }
}

// ── Void diff ───────────────────────────────────────────────────────

/// Void has no values, so Diff is trivially never called.
/// We need the impl for sum chains to terminate.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum VoidDiff {}

impl DiffInfo for VoidDiff {
    fn is_empty(&self) -> bool {
        match *self {}
    }
    fn change_count(&self) -> usize {
        match *self {}
    }
}

impl Diff for Void {
    type Diff = VoidDiff;
    fn diff(old: &Self, _new: &Self) -> VoidDiff {
        match *old {}
    }
}

impl Patch for Void {
    fn patch(old: &Self, _diff: &VoidDiff) -> Self {
        match *old {}
    }
}

// ── Generic diff/patch convenience functions ────────────────────────

/// Compute a structural diff between two values via their generic representation.
///
/// Returns the diff of the representation type, which can be used with
/// [`generic_patch`] to transform `old` into `new`.
pub fn generic_diff<T>(old: &T, new: &T) -> <T::Repr as Diff>::Diff
where
    T: GenericRepr + Clone,
    T::Repr: Diff,
{
    let old_repr = old.clone().into_repr();
    let new_repr = new.clone().into_repr();
    T::Repr::diff(&old_repr, &new_repr)
}

/// Apply a structural diff to transform a value via its generic representation.
pub fn generic_patch<T>(old: &T, diff: &<T::Repr as Diff>::Diff) -> T
where
    T: GenericRepr + Clone,
    T::Repr: Patch,
{
    let old_repr = old.clone().into_repr();
    let patched_repr = T::Repr::patch(&old_repr, diff);
    T::from_repr(patched_repr)
}

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

    // ── Test types ────────────────────────────────────────────────

    #[derive(Clone, Debug, PartialEq)]
    struct Point {
        x: f64,
        y: f64,
    }

    impl GenericRepr for Point {
        type Repr = Product<Field<f64>, Product<Field<f64>, Unit>>;
        fn into_repr(self) -> Self::Repr {
            Product(
                Field::new("x", self.x),
                Product(Field::new("y", self.y), Unit),
            )
        }
        fn from_repr(repr: Self::Repr) -> Self {
            Point {
                x: repr.0.value,
                y: repr.1.0.value,
            }
        }
    }

    #[derive(Clone, Debug, PartialEq)]
    enum Color {
        Red,
        Green,
        Custom(u8, u8, u8),
    }

    impl GenericRepr for Color {
        type Repr = Sum<
            Variant<Unit>,
            Sum<Variant<Unit>, Sum<Variant<Product<u8, Product<u8, Product<u8, Unit>>>>, Void>>,
        >;

        fn into_repr(self) -> Self::Repr {
            match self {
                Color::Red => Sum::Left(Variant::new("Red", Unit)),
                Color::Green => Sum::Right(Sum::Left(Variant::new("Green", Unit))),
                Color::Custom(r, g, b) => Sum::Right(Sum::Right(Sum::Left(Variant::new(
                    "Custom",
                    Product(r, Product(g, Product(b, Unit))),
                )))),
            }
        }

        fn from_repr(repr: Self::Repr) -> Self {
            match repr {
                Sum::Left(_) => Color::Red,
                Sum::Right(Sum::Left(_)) => Color::Green,
                Sum::Right(Sum::Right(Sum::Left(v))) => {
                    Color::Custom(v.value.0, v.value.1.0, v.value.1.1.0)
                }
                Sum::Right(Sum::Right(Sum::Right(v))) => match v {},
            }
        }
    }

    // ── Leaf diff ─────────────────────────────────────────────────

    #[test]
    fn leaf_diff_same() {
        let d = i32::diff(&42, &42);
        assert!(d.is_same());
        assert!(d.is_empty());
        assert_eq!(d.change_count(), 0);
    }

    #[test]
    fn leaf_diff_changed() {
        let d = i32::diff(&1, &2);
        assert!(d.is_changed());
        assert!(!d.is_empty());
        assert_eq!(d.change_count(), 1);
    }

    #[test]
    fn leaf_patch_same() {
        let d = Delta::Same;
        assert_eq!(i32::patch(&42, &d), 42);
    }

    #[test]
    fn leaf_patch_changed() {
        let d = Delta::Changed(99);
        assert_eq!(i32::patch(&42, &d), 99);
    }

    // ── Product diff ──────────────────────────────────────────────

    #[test]
    fn product_diff_same() {
        let a = Product(1u32, Product(2u32, Unit));
        let d = <Product<u32, Product<u32, Unit>>>::diff(&a, &a);
        assert!(d.is_empty());
        assert_eq!(d.change_count(), 0);
    }

    #[test]
    fn product_diff_one_field() {
        let a = Product(1u32, Product(2u32, Unit));
        let b = Product(1u32, Product(3u32, Unit));
        let d = <Product<u32, Product<u32, Unit>>>::diff(&a, &b);
        assert!(!d.is_empty());
        assert_eq!(d.change_count(), 1);
        assert!(d.head.is_same());
        assert!(d.tail.head.is_changed());
    }

    #[test]
    fn product_patch_roundtrip() {
        let a = Product(1u32, Product(2u32, Unit));
        let b = Product(3u32, Product(2u32, Unit));
        let d = <Product<u32, Product<u32, Unit>>>::diff(&a, &b);
        let patched = <Product<u32, Product<u32, Unit>>>::patch(&a, &d);
        assert_eq!(patched, b);
    }

    // ── Sum diff ──────────────────────────────────────────────────

    #[test]
    fn sum_diff_same_variant() {
        let a: Sum<u32, u32> = Sum::Left(42);
        let b: Sum<u32, u32> = Sum::Left(42);
        let d = <Sum<u32, u32>>::diff(&a, &b);
        assert!(d.is_empty());
    }

    #[test]
    fn sum_diff_same_variant_different_value() {
        let a: Sum<u32, u32> = Sum::Left(1);
        let b: Sum<u32, u32> = Sum::Left(2);
        let d = <Sum<u32, u32>>::diff(&a, &b);
        assert!(!d.is_empty());
        assert_eq!(d.change_count(), 1);
    }

    #[test]
    fn sum_diff_variant_changed() {
        let a: Sum<u32, u32> = Sum::Left(1);
        let b: Sum<u32, u32> = Sum::Right(2);
        let d = <Sum<u32, u32>>::diff(&a, &b);
        assert!(!d.is_empty());
        assert_eq!(d.change_count(), 1);
    }

    #[test]
    fn sum_patch_same_variant() {
        let a: Sum<u32, u32> = Sum::Left(1);
        let b: Sum<u32, u32> = Sum::Left(2);
        let d = <Sum<u32, u32>>::diff(&a, &b);
        let patched = <Sum<u32, u32>>::patch(&a, &d);
        assert_eq!(patched, b);
    }

    #[test]
    fn sum_patch_variant_change() {
        let a: Sum<u32, u32> = Sum::Left(1);
        let b: Sum<u32, u32> = Sum::Right(99);
        let d = <Sum<u32, u32>>::diff(&a, &b);
        let patched = <Sum<u32, u32>>::patch(&a, &d);
        assert_eq!(patched, b);
    }

    // ── Generic diff/patch on Point ───────────────────────────────

    #[test]
    fn point_diff_same() {
        let p = Point { x: 1.0, y: 2.0 };
        let d = generic_diff(&p, &p);
        assert!(d.is_empty());
    }

    #[test]
    fn point_diff_one_field_changed() {
        let a = Point { x: 1.0, y: 2.0 };
        let b = Point { x: 1.0, y: 3.0 };
        let d = generic_diff(&a, &b);
        assert!(!d.is_empty());
        assert_eq!(d.change_count(), 1);
    }

    #[test]
    fn point_diff_both_fields_changed() {
        let a = Point { x: 1.0, y: 2.0 };
        let b = Point { x: 3.0, y: 4.0 };
        let d = generic_diff(&a, &b);
        assert_eq!(d.change_count(), 2);
    }

    #[test]
    fn point_patch_roundtrip() {
        let a = Point { x: 1.0, y: 2.0 };
        let b = Point { x: 3.0, y: 4.0 };
        let d = generic_diff(&a, &b);
        let patched = generic_patch(&a, &d);
        assert_eq!(patched, b);
    }

    #[test]
    fn point_patch_identity() {
        let p = Point { x: 1.0, y: 2.0 };
        let d = generic_diff(&p, &p);
        let patched = generic_patch(&p, &d);
        assert_eq!(patched, p);
    }

    // ── Generic diff/patch on Color enum ──────────────────────────

    #[test]
    fn color_diff_same_unit_variant() {
        let d = generic_diff(&Color::Red, &Color::Red);
        assert!(d.is_empty());
    }

    #[test]
    fn color_diff_different_unit_variants() {
        let d = generic_diff(&Color::Red, &Color::Green);
        assert!(!d.is_empty());
    }

    #[test]
    fn color_diff_same_data_variant() {
        let a = Color::Custom(255, 128, 0);
        let d = generic_diff(&a, &a);
        assert!(d.is_empty());
    }

    #[test]
    fn color_diff_data_variant_changed() {
        let a = Color::Custom(255, 128, 0);
        let b = Color::Custom(255, 0, 0);
        let d = generic_diff(&a, &b);
        assert!(!d.is_empty());
    }

    #[test]
    fn color_patch_variant_change() {
        let a = Color::Red;
        let b = Color::Custom(1, 2, 3);
        let d = generic_diff(&a, &b);
        let patched = generic_patch(&a, &d);
        assert_eq!(patched, b);
    }

    #[test]
    fn color_patch_roundtrip_all() {
        let variants = [Color::Red, Color::Green, Color::Custom(10, 20, 30)];
        for old in &variants {
            for new in &variants {
                let d = generic_diff(old, new);
                let patched = generic_patch(old, &d);
                assert_eq!(&patched, new, "failed: {old:?} -> {new:?}");
            }
        }
    }

    // ── Delta debug ───────────────────────────────────────────────

    #[test]
    fn delta_debug_same() {
        let d: Delta<i32> = Delta::Same;
        assert_eq!(format!("{d:?}"), "Same");
    }

    #[test]
    fn delta_debug_changed() {
        let d = Delta::Changed(42);
        assert_eq!(format!("{d:?}"), "Changed(42)");
    }

    // ── DiffInfo on product ───────────────────────────────────────

    #[test]
    fn product_diff_change_count() {
        let a = Product(1u32, Product(2u32, Product(3u32, Unit)));
        let b = Product(1u32, Product(9u32, Product(9u32, Unit)));
        let d = <Product<u32, Product<u32, Product<u32, Unit>>>>::diff(&a, &b);
        assert_eq!(d.change_count(), 2);
    }

    // ── Proptest property tests ──────────────────────────────────

    mod proptests {
        use super::*;
        use proptest::prelude::*;

        fn arb_point() -> impl Strategy<Value = Point> {
            (any::<f64>(), any::<f64>()).prop_map(|(x, y)| Point { x, y })
        }

        fn arb_color() -> impl Strategy<Value = Color> {
            prop_oneof![
                Just(Color::Red),
                Just(Color::Green),
                (any::<u8>(), any::<u8>(), any::<u8>())
                    .prop_map(|(r, g, b)| Color::Custom(r, g, b)),
            ]
        }

        proptest! {
            #[test]
            fn point_roundtrip(old in arb_point(), new in arb_point()) {
                let d = generic_diff(&old, &new);
                let patched = generic_patch(&old, &d);
                prop_assert_eq!(patched, new);
            }

            #[test]
            fn point_self_diff_is_empty(p in arb_point()) {
                let d = generic_diff(&p, &p);
                prop_assert!(d.is_empty());
            }

            #[test]
            fn point_self_patch_is_identity(p in arb_point()) {
                let d = generic_diff(&p, &p);
                let patched = generic_patch(&p, &d);
                prop_assert_eq!(patched, p);
            }

            #[test]
            fn color_roundtrip(old in arb_color(), new in arb_color()) {
                let d = generic_diff(&old, &new);
                let patched = generic_patch(&old, &d);
                prop_assert_eq!(patched, new);
            }

            #[test]
            fn color_self_diff_is_empty(c in arb_color()) {
                let d = generic_diff(&c, &c);
                prop_assert!(d.is_empty());
            }

            #[test]
            fn color_self_patch_is_identity(c in arb_color()) {
                let d = generic_diff(&c, &c);
                let patched = generic_patch(&c, &d);
                prop_assert_eq!(patched, c);
            }

            #[test]
            fn leaf_i32_roundtrip(old in any::<i32>(), new in any::<i32>()) {
                let d = i32::diff(&old, &new);
                let patched = i32::patch(&old, &d);
                prop_assert_eq!(patched, new);
            }

            #[test]
            fn leaf_i32_self_diff_empty(v in any::<i32>()) {
                let d = i32::diff(&v, &v);
                prop_assert!(d.is_empty());
                prop_assert_eq!(d.change_count(), 0);
            }

            #[test]
            fn product_u32_triple_roundtrip(
                a0 in any::<u32>(), a1 in any::<u32>(), a2 in any::<u32>(),
                b0 in any::<u32>(), b1 in any::<u32>(), b2 in any::<u32>(),
            ) {
                let old = Product(a0, Product(a1, Product(a2, Unit)));
                let new = Product(b0, Product(b1, Product(b2, Unit)));
                let d = <Product<u32, Product<u32, Product<u32, Unit>>>>::diff(&old, &new);
                let patched = <Product<u32, Product<u32, Product<u32, Unit>>>>::patch(&old, &d);
                prop_assert_eq!(patched, new);
            }

            #[test]
            fn sum_roundtrip(
                old_left in any::<bool>(), old_val in any::<u32>(),
                new_left in any::<bool>(), new_val in any::<u32>(),
            ) {
                let old: Sum<u32, u32> = if old_left { Sum::Left(old_val) } else { Sum::Right(old_val) };
                let new: Sum<u32, u32> = if new_left { Sum::Left(new_val) } else { Sum::Right(new_val) };
                let d = <Sum<u32, u32>>::diff(&old, &new);
                let patched = <Sum<u32, u32>>::patch(&old, &d);
                prop_assert_eq!(patched, new);
            }

            #[test]
            fn change_count_bounded_by_fields(
                old in arb_point(), new in arb_point()
            ) {
                let d = generic_diff(&old, &new);
                prop_assert!(d.change_count() <= 2);
            }

            #[test]
            fn diff_same_implies_zero_changes(p in arb_point()) {
                let d = generic_diff(&p, &p);
                prop_assert_eq!(d.change_count(), 0);
            }
        }
    }
}