use std::time::SystemTime;
use std::time::{Duration, Instant};
use once_cell::sync::Lazy;
static BEGINNING_OF_TIME: Lazy<(Instant, SystemTime)> = Lazy::new(|| {
let now = Instant::now();
let now_sys = SystemTime::now();
let beginning_of_time = {
let mut secs = 3600;
loop {
let dur = Duration::from_secs(secs);
if let Some(v) = now.checked_sub(dur) {
break v;
}
secs -= 1;
if secs == 0 {
panic!("Failed to find a beginning of time instant");
}
}
};
let since_beginning_of_time = Instant::now() - beginning_of_time;
let beginning_of_time_sys = now_sys - since_beginning_of_time;
(beginning_of_time, beginning_of_time_sys)
});
pub trait InstantExt {
fn to_unix_duration(&self) -> Duration;
}
impl InstantExt for Instant {
fn to_unix_duration(&self) -> Duration {
if *self < BEGINNING_OF_TIME.0 {
warn!("Time went backwards from beginning_of_time Instant");
}
let duration_since_time_0 = self.duration_since(BEGINNING_OF_TIME.0);
let system_time = BEGINNING_OF_TIME.1 + duration_since_time_0;
system_time
.duration_since(SystemTime::UNIX_EPOCH)
.expect("clock to go forwards from unix epoch")
}
}