Skip to main content

co_primitives/types/
clock.rs

1// SPDX-License-Identifier: AGPL-3.0-only
2// Copyright (C) 2026 1io BRANDGUARDIAN GmbH
3
4use serde::{Deserialize, Serialize};
5
6/// Lamport Clock.
7#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
8pub struct Clock {
9	#[serde(rename = "i", with = "serde_bytes")]
10	pub id: Vec<u8>,
11	#[serde(rename = "t")]
12	pub time: u64,
13}
14impl Clock {
15	pub fn new(id: Vec<u8>, time: u64) -> Self {
16		Self { id, time }
17	}
18
19	pub fn next(&self) -> Clock {
20		Clock { id: self.id.clone(), time: self.time + 1 }
21	}
22}
23impl PartialOrd for Clock {
24	fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
25		Some(self.cmp(other))
26	}
27}
28impl Ord for Clock {
29	fn cmp(&self, other: &Self) -> std::cmp::Ordering {
30		match self.time.cmp(&other.time) {
31			core::cmp::Ordering::Equal => {},
32			ord => return ord,
33		}
34		self.id.cmp(&other.id)
35	}
36}