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
use std::cmp::{Ordering};

use super::GCounter;

use rustc_serialize::{Encodable, Decodable};

/// `PNCounter` allows the counter to be both incremented and decremented
/// by representing the increments (P) and the decrements (N) in separate
/// internal G-Counters.
///
/// Merge is implemented by merging the internal P and N counters.
/// The value of the counter is P minus N.
///
/// # Examples
///
/// ```
/// use crdts::PNCounter;
/// let mut a = PNCounter::new();
/// a.increment("A".to_string());
/// a.increment("A".to_string());
/// a.decrement("A".to_string());
/// a.increment("A".to_string());
/// assert_eq!(a.value(), 2);
/// ```

#[derive(Debug, Eq, Clone, Hash, RustcEncodable, RustcDecodable)]
pub struct PNCounter<A: Ord + Clone + Encodable + Decodable> {
    p: GCounter<A>,
    n: GCounter<A>,
}

impl<A: Ord + Clone + Encodable + Decodable> Ord for PNCounter<A> {
    fn cmp(&self, other: &PNCounter<A>) -> Ordering {
        let (c, oc) = (self.value(), other.value());
        c.cmp(&oc)
    }
}

impl<A: Ord + Clone + Encodable + Decodable> PartialOrd for PNCounter<A> {
    fn partial_cmp(&self, other: &PNCounter<A>) -> Option<Ordering> {
        Some(self.cmp(other))
    }
}

impl<A: Ord + Clone + Encodable + Decodable> PartialEq for PNCounter<A> {
    fn eq(&self, other: &PNCounter<A>) -> bool {
        let (c, oc) = (self.value(), other.value());
        c == oc
    }
}

impl<A: Ord + Clone + Encodable + Decodable> PNCounter<A> {
    /// Produces a new `PNCounter`.
    pub fn new() -> PNCounter<A> {
        PNCounter {
            p: GCounter::new(),
            n: GCounter::new(),
        }
    }

    /// Increments a particular actor's counter.
    pub fn increment(&mut self, actor: A) {
        self.p.increment(actor);
    }

    /// Decrements a particular actor's counter.
    pub fn decrement(&mut self, actor: A) {
        self.n.increment(actor);
    }

    /// Returns the current value of this counter (P-N).
    pub fn value(&self) -> i64 {
        self.p.value() as i64 - self.n.value() as i64
    }

    /// Merge another pncounter into this one, without
    /// regard to dominance.
    ///
    /// # Examples
    ///
    /// ```
    /// use crdts::PNCounter;
    /// let (mut a, mut b, mut c) = (PNCounter::new(), PNCounter::new(), PNCounter::new());
    /// a.increment("A".to_string());
    /// b.increment("B".to_string());
    /// b.increment("B".to_string());
    /// b.decrement("A".to_string());
    /// c.increment("B".to_string());
    /// c.increment("B".to_string());
    /// a.merge(b);
    /// assert_eq!(a, c);
    pub fn merge(&mut self, other: PNCounter<A>) {
        self.p.merge(other.p);
        self.n.merge(other.n);
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use quickcheck::{Arbitrary, Gen, QuickCheck, StdGen};
    use std::collections::BTreeSet;
    use rand::{self, Rng};

    use ::GCounter;

    const ACTOR_MAX: u16 = 11;
    #[derive(Debug, Clone)]
    enum Op {
        Increment(i16),
        Decrement(i16),
    }

    impl Arbitrary for Op {
        fn arbitrary<G: Gen>(g: &mut G) -> Op {
            if g.gen_weighted_bool(2) {
                Op::Increment(g.gen_range(0, ACTOR_MAX) as i16)
            } else {
                Op::Decrement(g.gen_range(0, ACTOR_MAX) as i16)
            }
        }

        fn shrink(&self) -> Box<Iterator<Item=Op>> {
            Box::new(vec![].into_iter())
        }
    }

    #[derive(Debug, Clone)]
    struct OpVec {
        ops: Vec<Op>,
    }

    impl Arbitrary for OpVec {
        fn arbitrary<G: Gen>(g: &mut G )-> OpVec {
            let mut ops = vec![];
            for _ in 0..g.gen_range(1, 100) {
                ops.push(Op::arbitrary(g));
            }
            OpVec {
                ops: ops,
            }
        }

        fn shrink(&self) -> Box<Iterator<Item=OpVec>> {
            let mut smaller = vec![];
            for i in 0..self.ops.len() {
                let mut clone = self.clone();
                clone.ops.remove(i);
                smaller.push(clone);
            }

            Box::new(smaller.into_iter())
        }
    }

    fn prop_merge_converges(ops: OpVec) -> bool {
        let mut results = BTreeSet::new();

        // Permute the interleaving of operations should converge.
        // Largely taken directly from orswot
        for i in 2..ACTOR_MAX {
            let mut witnesses: Vec<PNCounter<i16>> = (0..i).map(|_| PNCounter::new()).collect();
            for op in ops.ops.iter() {
                match op {
                    &Op::Increment(actor) => {
                        witnesses[(actor as usize % i as usize)].increment(actor);
                    },
                    &Op::Decrement(actor) => {
                        witnesses[(actor as usize % i as usize)].decrement(actor);
                    },
                }
            }
            let mut merged = PNCounter::new();
            for witness in witnesses.iter() {
                merged.merge(witness.clone());
            }

            results.insert(merged.value());
            if results.len() > 1 {
                println!("opvec: {:?}", ops);
                println!("results: {:?}", results);
                println!("witnesses: {:?}", &witnesses);
                println!("merged: {:?}", merged);
            }
        }
        results.len() == 1
    }


    #[test]
    fn qc_merge_converges() {
        QuickCheck::new()
                   .gen(StdGen::new(rand::thread_rng(), 1))
                   .tests(1_000)
                   .max_tests(10_000)
                   .quickcheck(prop_merge_converges as fn(OpVec) -> bool);
    }


    #[test]
    fn test_basic() {
        let mut a = PNCounter::new();
        assert_eq!(a.value(), 0);
        a.increment("A".to_string());
        assert_eq!(a.value(), 1);
        a.increment("A".to_string());
        assert_eq!(a.value(), 2);
        a.decrement("A".to_string());
        assert_eq!(a.value(), 1);
        a.increment("A".to_string());
        assert_eq!(a.value(), 2);
    }
}