use core::ops::Add;
use std::time::{UNIX_EPOCH, SystemTime, Instant, Duration};
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub struct CanonicalInstant {
time: u64,
instant: Instant,
}
pub(crate) fn sys_time(time: u64) -> SystemTime {
UNIX_EPOCH + Duration::from_secs(time)
}
impl CanonicalInstant {
pub fn new(time: u64) -> CanonicalInstant {
let instant_now = Instant::now();
let sys_now = SystemTime::now();
let elapsed = sys_now.duration_since(sys_time(time)).unwrap_or(Duration::ZERO);
let synced_instant = instant_now.checked_sub(elapsed).unwrap();
CanonicalInstant { time, instant: synced_instant }
}
pub fn canonical(&self) -> u64 {
self.time
}
pub fn instant(&self) -> Instant {
self.instant
}
}
impl Add<Duration> for CanonicalInstant {
type Output = CanonicalInstant;
fn add(self, duration: Duration) -> CanonicalInstant {
CanonicalInstant { time: self.time + duration.as_secs(), instant: self.instant + duration }
}
}