hlc_id/
clock.rs

1use serde::{Serialize, Deserialize};
2use std::fs::{File, OpenOptions};
3use std::io::Read;
4
5#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
6pub struct HybridLogicalClock {
7    timestamp: u64,
8    sequence: u16,
9    node_id: u16,
10    initialized: bool,
11}
12
13impl HybridLogicalClock {
14    pub fn new(node_id: u16) -> Self {
15        Self {
16            timestamp: 0,
17            sequence: 0,
18            node_id,
19            initialized: false,
20        }
21    }
22
23    pub fn update(&mut self, external_timestamp: u64) {
24        if !self.initialized || external_timestamp > self.timestamp {
25            self.timestamp = external_timestamp;
26            self.sequence = 0;
27            self.initialized = true;
28        } else if external_timestamp == self.timestamp {
29            self.sequence += 1;
30        } else {
31            self.timestamp = external_timestamp;
32            self.sequence = 0;
33        }
34    }
35
36    pub fn process_timestamp(&mut self, received_timestamp: u64) {
37        if received_timestamp > self.timestamp {
38            self.update(received_timestamp);
39        }
40    }
41
42    pub fn save_state(&self, path: &str) -> std::io::Result<()> {
43        let file = OpenOptions::new().write(true).create(true).open(path)?;
44        serde_json::to_writer(file, &self)?;
45        Ok(())
46    }
47
48    pub fn load_state(path: &str) -> std::io::Result<Self> {
49        let mut file = File::open(path)?;
50        let mut data = String::new();
51        file.read_to_string(&mut data)?;
52        Ok(serde_json::from_str(&data)?)
53    }
54
55    pub fn current_timestamp(&self) -> u64 {
56        self.timestamp
57    }
58
59    pub fn node_id(&self) -> u16 {
60        self.node_id
61    }
62
63    pub fn current_sequence(&self) -> u16 {
64        self.sequence
65    }
66}