Skip to main content

logicaffeine_data/crdt/causal/
vclock.rs

1//! Vector Clock for causal ordering.
2//!
3//! VClock tracks causality between distributed events.
4
5use super::super::replica::ReplicaId;
6use super::super::Merge;
7use serde::{Deserialize, Serialize};
8use std::collections::HashMap;
9
10/// A vector clock for tracking causal relationships between events.
11///
12/// Each replica has a logical clock counter. The vector clock captures
13/// which events have been "seen" by tracking the maximum counter for each replica.
14#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
15pub struct VClock {
16    entries: HashMap<ReplicaId, u64>,
17}
18
19impl VClock {
20    /// Create a new empty vector clock.
21    pub fn new() -> Self {
22        Self::default()
23    }
24
25    /// Increment the clock for a replica and return the new counter value.
26    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    /// Get the current counter for a replica (0 if not seen).
33    pub fn get(&self, replica: ReplicaId) -> u64 {
34        *self.entries.get(&replica).unwrap_or(&0)
35    }
36
37    /// Check if self dominates other (self >= other for all replicas).
38    ///
39    /// Returns true if for every replica in `other`, self has an equal or greater counter.
40    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    /// Check if self and other are concurrent (neither dominates the other).
50    pub fn concurrent(&self, other: &Self) -> bool {
51        !self.dominates(other) && !other.dominates(self)
52    }
53
54    /// Merge another vector clock into this one (pointwise max).
55    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    /// The sum of every replica's counter — the number of events the clock covers.
63    pub fn total(&self) -> u64 {
64        self.entries.values().sum()
65    }
66
67    /// Get all replicas in this clock.
68    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;