#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct Timestamp(u64);
impl Timestamp {
#[inline]
pub const fn from_nanos(nanos: u64) -> Self {
Self(nanos)
}
#[inline]
pub const fn as_nanos(&self) -> u64 {
self.0
}
}
#[cfg(feature = "std")]
impl From<std::time::SystemTime> for Timestamp {
fn from(t: std::time::SystemTime) -> Self {
let nanos = t
.duration_since(std::time::UNIX_EPOCH)
.expect("system time before Unix epoch")
.as_nanos() as u64;
Self(nanos)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn round_trips_nanos() {
let ts = Timestamp::from_nanos(1_000_000_000);
assert_eq!(ts.as_nanos(), 1_000_000_000);
}
#[cfg(feature = "std")]
#[test]
fn from_system_time_at_epoch_is_zero() {
let ts = Timestamp::from(std::time::SystemTime::UNIX_EPOCH);
assert_eq!(ts.as_nanos(), 0);
}
}