use derive_more::{Deref, Display};
#[repr(transparent)]
#[derive(Debug, Display, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Deref)]
#[display("{}.{}", self.millis(), self.counter())]
pub struct HlcTimestamp(
u64,
);
impl HlcTimestamp {
pub const MAX: Self = Self(u64::MAX);
#[inline]
pub const fn new(millis: u64, counter: u16) -> Self {
Self((millis << 16) | (counter as u64))
}
#[inline]
pub const fn millis(&self) -> u64 {
self.0 >> 16
}
#[inline]
pub const fn counter(&self) -> u16 {
(self.0 & 0xFFFF) as u16
}
#[inline]
pub const fn from_u64(val: u64) -> Self {
Self(val)
}
}
pub struct HlcGenerator {
last_timestamp: HlcTimestamp,
}
impl HlcGenerator {
pub fn new() -> Self {
Self {
last_timestamp: HlcTimestamp(0),
}
}
pub fn generate(&mut self, now_ms: u64) -> HlcTimestamp {
let last_ms = self.last_timestamp.millis();
if now_ms > last_ms {
self.last_timestamp = HlcTimestamp::new(now_ms, 0);
} else {
self.last_timestamp.0 += 1;
}
self.last_timestamp
}
}