use std::fmt;
use std::ops::Sub;
use std::time::Duration;
use super::{phys_now_ms, Seq, Stamp};
impl Seq {
pub const FIRST: Seq = Seq(1);
pub const NONE: Seq = Seq(0);
#[allow(dead_code)] pub const fn new(value: u64) -> Seq {
Seq(value)
}
pub fn to_le_bytes(self) -> [u8; 8] {
self.0.to_le_bytes()
}
pub fn from_le_bytes(bytes: [u8; 8]) -> Seq {
Seq(u64::from_le_bytes(bytes))
}
}
impl fmt::Display for Seq {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Display::fmt(&self.0, f)
}
}
impl Sub for Seq {
type Output = u64;
fn sub(self, rhs: Seq) -> u64 {
self.0 - rhs.0
}
}
impl Stamp {
pub const NONE: Stamp = Stamp(0);
#[allow(dead_code)] pub const fn new(value: u64) -> Stamp {
Stamp(value)
}
pub fn to_le_bytes(self) -> [u8; 8] {
self.0.to_le_bytes()
}
pub fn from_le_bytes(bytes: [u8; 8]) -> Stamp {
Stamp(u64::from_le_bytes(bytes))
}
pub(super) fn now() -> Stamp {
Stamp(phys_now_ms())
}
pub(super) fn is_fresh(self, now: Stamp, window: Duration) -> bool {
let window_ms = window.as_millis() as u64;
self.age_relative_to(now) <= window_ms && now.age_relative_to(self) <= window_ms
}
pub(super) fn age_relative_to(self, now: Stamp) -> u64 {
now.0.saturating_sub(self.0)
}
}
impl fmt::Display for Stamp {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Display::fmt(&self.0, f)
}
}