crdt_kit/crdt.rs
1/// Core trait that all CRDTs must implement.
2///
3/// A CRDT (Conflict-free Replicated Data Type) guarantees that concurrent
4/// updates on different replicas will converge to the same state after merging,
5/// without requiring coordination.
6///
7/// # Properties
8///
9/// All implementations must satisfy:
10/// - **Commutativity:** `a.merge(b) == b.merge(a)`
11/// - **Associativity:** `a.merge(b.merge(c)) == a.merge(b).merge(c)`
12/// - **Idempotency:** `a.merge(a) == a`
13pub trait Crdt {
14 /// Merge another replica's state into this one.
15 ///
16 /// After merging, `self` contains the least upper bound of both states.
17 /// This operation is commutative, associative, and idempotent.
18 fn merge(&mut self, other: &Self);
19}
20
21/// Extension trait for delta-state CRDTs.
22///
23/// Delta-state CRDTs can produce compact deltas representing only the
24/// changes between two states. This enables efficient synchronization:
25/// instead of transferring the full state, replicas exchange small deltas.
26///
27/// # Example
28///
29/// ```
30/// use crdt_kit::prelude::*;
31///
32/// let mut c1 = GCounter::new("a");
33/// c1.increment();
34/// c1.increment();
35///
36/// let mut c2 = GCounter::new("b");
37/// c2.increment();
38///
39/// // Generate a delta from c1 that c2 doesn't have
40/// let delta = c1.delta(&c2);
41///
42/// // Apply just the delta instead of full state merge
43/// c2.apply_delta(&delta);
44/// assert_eq!(c2.value(), 3); // both counts included
45/// ```
46pub trait DeltaCrdt: Crdt {
47 /// The type of delta produced by this CRDT.
48 type Delta;
49
50 /// Generate a delta containing changes in `self` that `other` does not have.
51 ///
52 /// The returned delta is the minimal set of information needed to bring
53 /// a replica at state `other` up to date with `self`.
54 fn delta(&self, other: &Self) -> Self::Delta;
55
56 /// Apply a delta to this replica's state.
57 ///
58 /// This is equivalent to merging the state that produced the delta,
59 /// but typically much more efficient in terms of data transferred.
60 fn apply_delta(&mut self, delta: &Self::Delta);
61}