use std::{
sync::{Arc, Mutex},
time::{Duration, Instant, SystemTime},
};
use crate::Time;
#[derive(Debug)]
pub struct StaticTimeSource {
now: SystemTime,
now_instant: Instant,
}
impl StaticTimeSource {
pub fn at_time(time: impl Into<SystemTime>) -> Self {
Self {
now: time.into(),
now_instant: Instant::now(),
}
}
}
impl Time for StaticTimeSource {
fn now(&self) -> SystemTime {
self.now
}
fn instant(&self) -> Instant {
self.now_instant
}
}
#[derive(Debug, Clone)]
pub struct ManuallyAdvancedTimeSource(Arc<Mutex<StaticTimeSource>>);
impl ManuallyAdvancedTimeSource {
pub fn at_time(time: impl Into<SystemTime>) -> Self {
let ts = StaticTimeSource::at_time(time);
Self(Arc::from(Mutex::from(ts)))
}
pub fn update_time(&self, time: impl Into<SystemTime>) {
let mut guard = self.0.lock().unwrap();
guard.now = time.into();
}
pub fn update_instant(&self, elapsed: Duration) {
let mut guard = self.0.lock().unwrap();
guard.now_instant += elapsed;
}
}
impl Time for ManuallyAdvancedTimeSource {
fn now(&self) -> SystemTime {
self.0.lock().unwrap().now
}
fn instant(&self) -> Instant {
self.0.lock().unwrap().now_instant
}
}