#[cfg(not(feature = "ash-time"))]
use std::sync::atomic::{AtomicU64, Ordering};
#[cfg(feature = "ash-time")]
use crate::error::Error;
use crate::error::Result;
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Stamp {
pub physical: u64,
pub logical: u64,
}
#[cfg(feature = "ash-time")]
impl From<ash_time::HlcTimestamp> for Stamp {
fn from(ts: ash_time::HlcTimestamp) -> Self {
Stamp {
physical: ts.physical,
logical: ts.logical as u64,
}
}
}
pub struct Clock {
#[cfg(feature = "ash-time")]
hlc: ash_time::HlcClock,
#[cfg(not(feature = "ash-time"))]
counter: AtomicU64,
}
impl Clock {
pub fn new() -> Self {
#[cfg(feature = "ash-time")]
{
Self {
hlc: ash_time::HlcClock::new(),
}
}
#[cfg(not(feature = "ash-time"))]
{
Self {
counter: AtomicU64::new(0),
}
}
}
pub fn stamp(&self) -> Result<Stamp> {
#[cfg(feature = "ash-time")]
{
self.hlc
.now()
.map(Stamp::from)
.map_err(|e| Error::cluster(format!("hlc clock error: {e}")))
}
#[cfg(not(feature = "ash-time"))]
{
let logical = self.counter.fetch_add(1, Ordering::Relaxed) + 1;
Ok(Stamp {
physical: 0,
logical,
})
}
}
}
impl Default for Clock {
fn default() -> Self {
Self::new()
}
}