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
//! The `vclock` crate provides a generic vector clock implementation.
//!
//! # Examples
//!
//! ```
//! use crdts::VClock;
//! let (mut a, mut b) = (VClock::new(), VClock::new());
//! a.witness("A".to_string(), 2);
//! b.witness("A".to_string(), 1);
//! assert!(a > b);
//! ```

use super::*;

use std::cmp::Ordering;
use std::collections::BTreeMap;

/// A counter is used to track causality at a particular actor.
pub type Counter = u64;

trait AddableU64 {
    fn add_u64(&mut self, other: u64) -> Self;
}

/// A `VClock` is a standard vector clock.
/// It contains a set of "actors" and associated counters.
/// When a particular actor witnesses a mutation, their associated
/// counter in a `VClock` is incremented. `VClock` is typically used
/// as metadata for associated application data, rather than as the
/// container for application data. `VClock` just tracks causality.
/// It can tell you if something causally descends something else,
/// or if different replicas are "concurrent" (were mutated in
/// isolation, and need to be resolved externally).
#[serde(bound(deserialize = ""))]
#[derive(Debug, Clone, Ord, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct VClock<A: Ord + Clone + Serialize + DeserializeOwned> {
    /// dots is the mapping from actors to their associated counters
    pub dots: BTreeMap<A, Counter>,
}

impl<A: Ord + Clone + Serialize + DeserializeOwned> PartialOrd for VClock<A> {
    fn partial_cmp(&self, other: &VClock<A>) -> Option<Ordering> {
        if self == other {
            Some(Ordering::Equal)
        } else if other.dots.iter().all(|(w, c)| {
            self.contains_descendent_element(w, c)
        })
        {
            Some(Ordering::Greater)
        } else if self.dots.iter().all(|(w, c)| {
            other.contains_descendent_element(w, c)
        })
        {
            Some(Ordering::Less)
        } else {
            None
        }
    }
}

impl<A: Ord + Clone + Serialize + DeserializeOwned> VClock<A> {
    /// Returns a new `VClock` instance.
    pub fn new() -> VClock<A> {
        VClock { dots: BTreeMap::new() }
    }

    /// For a particular actor, possibly store a new counter
    /// if it dominates.
    ///
    /// # Examples
    ///
    /// ```
    /// use crdts::VClock;
    /// let (mut a, mut b) = (VClock::new(), VClock::new());
    /// a.witness("A".to_string(), 2);
    /// a.witness("A".to_string(), 0); // ignored because 2 dominates 0
    /// b.witness("A".to_string(), 1);
    /// assert!(a > b);
    /// ```
    ///
    pub fn witness(&mut self, actor: A, counter: Counter) -> Result<(), ()> {
        if !self.contains_descendent_element(&actor, &counter) {
            self.dots.insert(actor, counter);
            Ok(())
        } else {
            Err(())
        }
    }

    /// For a particular actor, increment the associated counter.
    ///
    /// # Examples
    ///
    /// ```
    /// use crdts::VClock;
    /// let (mut a, mut b) = (VClock::new(), VClock::new());
    /// a.increment("A".to_string());
    /// a.increment("A".to_string());
    /// a.witness("A".to_string(), 0); // ignored because 2 dominates 0
    /// b.increment("A".to_string());
    /// assert!(a > b);
    /// ```
    ///
    pub fn increment(&mut self, actor: A) -> Counter {
        let next = self.dots.get(&actor).map(|c| *c).unwrap_or(0) + 1;
        self.dots.insert(actor, next);
        next
    }

    /// Merge another vector clock into this one, without
    /// regard to dominance.
    ///
    /// # Examples
    ///
    /// ```
    /// use crdts::VClock;
    /// let (mut a, mut b, mut c) = (VClock::new(), VClock::new(), VClock::new());
    /// a.increment("A".to_string());
    /// b.increment("B".to_string());
    /// c.increment("A".to_string());
    /// c.increment("B".to_string());
    /// a.merge(b);
    /// assert_eq!(a, c);
    /// ```
    ///
    #[allow(unused_must_use)]
    pub fn merge(&mut self, other: VClock<A>) {
        for (actor, counter) in other.dots.into_iter() {
            self.witness(actor, counter);
        }
    }

    /// Determine if a single element is present and descendent.
    /// Generally prefer using the higher-level comparison operators
    /// between vclocks over this specific method.
    #[inline]
    pub fn contains_descendent_element(
        &self,
        actor: &A,
        counter: &Counter,
    ) -> bool {
        self.dots
            .get(actor)
            .map(|our_counter| our_counter >= counter)
            .unwrap_or(false)
    }

    /// True if two vector clocks have diverged.
    ///
    /// # Examples
    ///
    /// ```
    /// use crdts::VClock;
    /// let (mut a, mut b) = (VClock::new(), VClock::new());
    /// a.increment("A".to_string());
    /// b.increment("B".to_string());
    /// assert!(a.concurrent(&b));
    /// ```
    pub fn concurrent(&self, other: &VClock<A>) -> bool {
        self.partial_cmp(other).is_none()
    }

    /// Return the associated counter for this actor, if present.
    pub fn get(&self, actor: &A) -> Option<Counter> {
        self.dots.get(actor).map(|counter| *counter)
    }

    /// Returns `true` if this vector clock contains nothing.
    pub fn is_empty(&self) -> bool {
        self.dots.is_empty()
    }

    /// Return the dots that self dominates compared to another clock.
    pub fn dominating_dots(
        &self,
        dots: &BTreeMap<A, Counter>,
    ) -> BTreeMap<A, Counter> {
        let mut ret = BTreeMap::new();
        for (actor, counter) in self.dots.iter() {
            let other = dots.get(actor).map(|c| *c).unwrap_or(0);
            if *counter > other {
                ret.insert(actor.clone(), *counter);
            }
        }
        ret
    }

    /// Return a new `VClock` that contains the entries for which we have
    /// a counter that dominates another `VClock`.
    ///
    /// # Examples
    ///
    /// ```
    /// use crdts::VClock;
    /// let (mut a, mut b) = (VClock::new(), VClock::new());
    /// a.witness("A".to_string(), 3);
    /// a.witness("B".to_string(), 2);
    /// a.witness("D".to_string(), 14);
    /// a.witness("G".to_string(), 22);
    ///
    /// b.witness("A".to_string(), 4);
    /// b.witness("B".to_string(), 1);
    /// b.witness("C".to_string(), 1);
    /// b.witness("D".to_string(), 14);
    /// b.witness("E".to_string(), 5);
    /// b.witness("F".to_string(), 2);
    ///
    /// let dom = a.dominating_vclock(&b);
    /// assert_eq!(dom.get(&"B".to_string()), Some(2));
    /// assert_eq!(dom.get(&"G".to_string()), Some(22));
    /// ```
    pub fn dominating_vclock(&self, other: &VClock<A>) -> VClock<A> {
        let dots = self.dominating_dots(&other.dots);
        VClock { dots: dots }
    }

    /// Returns the common elements (same actor and counter)
    /// for two `VClock` instances.
    pub fn intersection(&self, other: &VClock<A>) -> VClock<A> {
        let mut dots = BTreeMap::new();
        for (actor, counter) in self.dots.iter() {
            if let Some(other_counter) = other.dots.get(actor) {
                if other_counter == counter {
                    dots.insert(actor.clone(), *counter);
                }
            }
        }
        VClock { dots: dots }
    }
}

#[cfg(test)]
mod tests {
    extern crate rand;
    extern crate quickcheck;

    use self::quickcheck::{Arbitrary, Gen};
    use super::*;

    impl Arbitrary for VClock<u16> {
        fn arbitrary<G: Gen>(g: &mut G) -> VClock<u16> {
            let mut v = VClock::new();
            for witness in 0..g.gen_range(0, 7) {
                v.witness(witness, g.gen_range(1, 7)).unwrap();
            }
            v
        }

        fn shrink(&self) -> Box<Iterator<Item = VClock<u16>>> {
            let mut smaller = vec![];
            for k in self.dots.keys() {
                let mut vc = self.clone();
                vc.dots.remove(k);
                smaller.push(vc)
            }
            Box::new(smaller.into_iter())
        }
    }

    #[test]
    fn test_merge() {
        let (mut a, mut b) = (VClock::new(), VClock::new());
        a.witness(1, 1).unwrap();
        a.witness(2, 2).unwrap();
        a.witness(4, 4).unwrap();

        b.witness(3, 3).unwrap();
        b.witness(4, 3).unwrap();

        a.merge(b);
        assert_eq!(a.get(&1), Some(1));
        assert_eq!(a.get(&2), Some(2));
        assert_eq!(a.get(&3), Some(3));
        assert_eq!(a.get(&4), Some(4));
    }

    #[test]
    fn test_merge_less_left() {
        let (mut a, mut b) = (VClock::new(), VClock::new());
        a.witness(5, 5).unwrap();

        b.witness(6, 6).unwrap();
        b.witness(7, 7).unwrap();

        a.merge(b);
        assert_eq!(a.get(&5), Some(5));
        assert_eq!(a.get(&6), Some(6));
        assert_eq!(a.get(&7), Some(7));
    }

    #[test]
    fn test_merge_less_right() {
        let (mut a, mut b) = (VClock::new(), VClock::new());
        a.witness(6, 6).unwrap();
        a.witness(7, 7).unwrap();

        b.witness(5, 5).unwrap();

        a.merge(b);
        assert_eq!(a.get(&5), Some(5));
        assert_eq!(a.get(&6), Some(6));
        assert_eq!(a.get(&7), Some(7));
    }

    #[test]
    fn test_merge_same_id() {
        let (mut a, mut b) = (VClock::new(), VClock::new());
        a.witness(1, 1).unwrap();
        a.witness(2, 1).unwrap();

        b.witness(1, 1).unwrap();
        b.witness(3, 1).unwrap();

        a.merge(b);
        assert_eq!(a.get(&1), Some(1));
        assert_eq!(a.get(&2), Some(1));
        assert_eq!(a.get(&3), Some(1));
    }

    #[test]
    fn test_vclock_ordering() {
        assert_eq!(VClock::<i8>::new(), VClock::new());

        let (mut a, mut b) = (VClock::new(), VClock::new());
        a.witness("A".to_string(), 1).unwrap();
        a.witness("A".to_string(), 2).unwrap();
        assert!(a.witness("A".to_string(), 0).is_err());
        b.witness("A".to_string(), 1).unwrap();

        // a {A:2}
        // b {A:1}
        // expect: a dominates
        assert!(a > b);
        assert!(b < a);
        assert!(a != b);

        b.witness("A".to_string(), 3).unwrap();
        // a {A:2}
        // b {A:3}
        // expect: b dominates
        assert!(b > a);
        assert!(a < b);
        assert!(a != b);

        a.witness("B".to_string(), 1).unwrap();
        // a {A:2, B:1}
        // b {A:3}
        // expect: concurrent
        assert!(a != b);
        assert!(!(a > b));
        assert!(!(b > a));

        a.witness("A".to_string(), 3).unwrap();
        // a {A:3, B:1}
        // b {A:3}
        // expect: a dominates
        assert!(a > b);
        assert!(b < a);
        assert!(a != b);

        b.witness("B".to_string(), 2).unwrap();
        // a {A:3, B:1}
        // b {A:3, B:2}
        // expect: b dominates
        assert!(b > a);
        assert!(a < b);
        assert!(a != b);

        a.witness("B".to_string(), 2).unwrap();
        // a {A:3, B:2}
        // b {A:3, B:2}
        // expect: equal
        assert!(!(b > a));
        assert!(!(a > b));
        assert_eq!(a, b);
    }
}