logicaffeine_data/crdt/causal/
vclock.rs1use super::super::replica::ReplicaId;
6use super::super::Merge;
7use serde::{Deserialize, Serialize};
8use std::collections::HashMap;
9
10#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
15pub struct VClock {
16 entries: HashMap<ReplicaId, u64>,
17}
18
19impl VClock {
20 pub fn new() -> Self {
22 Self::default()
23 }
24
25 pub fn increment(&mut self, replica: ReplicaId) -> u64 {
27 let entry = self.entries.entry(replica).or_insert(0);
28 *entry += 1;
29 *entry
30 }
31
32 pub fn get(&self, replica: ReplicaId) -> u64 {
34 *self.entries.get(&replica).unwrap_or(&0)
35 }
36
37 pub fn dominates(&self, other: &Self) -> bool {
41 for (&replica, &count) in &other.entries {
42 if self.get(replica) < count {
43 return false;
44 }
45 }
46 true
47 }
48
49 pub fn concurrent(&self, other: &Self) -> bool {
51 !self.dominates(other) && !other.dominates(self)
52 }
53
54 pub fn merge_vclock(&mut self, other: &Self) {
56 for (&replica, &count) in &other.entries {
57 let entry = self.entries.entry(replica).or_insert(0);
58 *entry = (*entry).max(count);
59 }
60 }
61
62 pub fn total(&self) -> u64 {
64 self.entries.values().sum()
65 }
66
67 pub fn replicas(&self) -> impl Iterator<Item = &ReplicaId> {
69 self.entries.keys()
70 }
71}
72
73impl Merge for VClock {
74 fn merge(&mut self, other: &Self) {
75 self.merge_vclock(other);
76 }
77}
78
79#[cfg(test)]
80#[path = "../../../../logicaffeine_tests/unit/logicaffeine_data/crdt/causal/vclock/tests.rs"]
81mod tests;