Files
DomiStream/crates/domistream/src/time.rs
T

40 lines
1.2 KiB
Rust

//! Time comes in from the caller as an [`Instant`]; DomiStream never reads a clock.
use core::time::Duration;
/// A point on the caller's monotonic clock, in microseconds since an epoch the caller chooses.
///
/// Only differences between instants matter. The caller must never let it go backwards within one session.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Instant(u64);
impl Instant {
/// The caller's epoch.
pub const ZERO: Self = Self(0);
/// An instant `micros` microseconds after the caller's epoch.
#[must_use]
pub const fn from_micros(micros: u64) -> Self {
Self(micros)
}
/// Microseconds since the caller's epoch.
#[must_use]
pub const fn as_micros(self) -> u64 {
self.0
}
/// `self + d`, saturating at the end of the clock.
#[must_use]
pub fn saturating_add(self, d: Duration) -> Self {
let micros = u64::try_from(d.as_micros()).unwrap_or(u64::MAX);
Self(self.0.saturating_add(micros))
}
/// `self - earlier`, or zero when `earlier` is later.
#[must_use]
pub fn saturating_duration_since(self, earlier: Self) -> Duration {
Duration::from_micros(self.0.saturating_sub(earlier.0))
}
}