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
use num_bigint::BigUint;
use serde::{Deserialize, Serialize};

use crate::{Actor, Causal, CmRDT, CvRDT, Dot, VClock};

/// `GCounter` is a grow-only witnessed counter.
///
/// # Examples
///
/// ```
/// use crdts::{GCounter, CmRDT};
///
/// let mut a = GCounter::new();
/// let mut b = GCounter::new();
///
/// a.apply(a.inc("A"));
/// b.apply(b.inc("B"));
///
/// assert_eq!(a.read(), b.read());
///
/// a.apply(a.inc("A"));
/// assert!(a.read() > b.read());
/// ```
#[derive(Debug, PartialEq, Eq, Clone, Hash, Serialize, Deserialize)]
pub struct GCounter<A: Actor> {
    inner: VClock<A>,
}

impl<A: Actor> Default for GCounter<A> {
    fn default() -> Self {
        Self::new()
    }
}

impl<A: Actor> CmRDT for GCounter<A> {
    type Op = Dot<A>;

    fn apply(&mut self, op: Self::Op) {
        self.inner.apply(op)
    }
}

impl<A: Actor> CvRDT for GCounter<A> {
    fn merge(&mut self, other: Self) {
        self.inner.merge(other.inner);
    }
}

impl<A: Actor> Causal<A> for GCounter<A> {
    fn forget(&mut self, clock: &VClock<A>) {
        self.inner.forget(&clock);
    }
}

impl<A: Actor> GCounter<A> {
    /// Produce a new `GCounter`.
    pub fn new() -> Self {
        Self {
            inner: VClock::new(),
        }
    }

    /// Generate Op to increment the counter.
    pub fn inc(&self, actor: A) -> Dot<A> {
        self.inner.inc(actor)
    }

    /// Return the current sum of this counter.
    pub fn read(&self) -> BigUint {
        self.inner.iter().map(|dot| dot.counter).sum()
    }
}

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

    #[test]
    fn test_basic() {
        let mut a = GCounter::new();
        let mut b = GCounter::new();
        a.apply(a.inc("A"));
        b.apply(b.inc("B"));

        assert_eq!(a.read(), b.read());
        assert_ne!(a, b);

        a.apply(a.inc("A"));

        assert_eq!(a.read(), b.read() + BigUint::from(1u8));
    }
}