use crate::time::{SharedTimeSource, TimeSource};
use crate::{
rt::sleep::{AsyncSleep, Sleep},
test_util::ManualTimeSource,
};
use std::sync::{Arc, Mutex};
use std::time::{Duration, SystemTime};
#[derive(Debug, Clone)]
pub struct InstantSleep {
log: Arc<Mutex<Vec<Duration>>>,
}
impl AsyncSleep for InstantSleep {
fn sleep(&self, duration: Duration) -> Sleep {
let log = self.log.clone();
Sleep::new(async move {
log.lock().unwrap().push(duration);
})
}
}
impl InstantSleep {
pub fn new(log: Arc<Mutex<Vec<Duration>>>) -> Self {
Self { log }
}
pub fn unlogged() -> Self {
Self {
log: Default::default(),
}
}
pub fn logs(&self) -> Vec<Duration> {
self.log.lock().unwrap().iter().cloned().collect()
}
pub fn total_duration(&self) -> Duration {
self.log.lock().unwrap().iter().sum()
}
}
pub fn instant_time_and_sleep(start_time: SystemTime) -> (ManualTimeSource, InstantSleep) {
let log = Arc::new(Mutex::new(vec![]));
let sleep = InstantSleep::new(log.clone());
(ManualTimeSource { start_time, log }, sleep)
}
impl TimeSource for SystemTime {
fn now(&self) -> SystemTime {
*self
}
}
impl From<SystemTime> for SharedTimeSource {
fn from(value: SystemTime) -> Self {
SharedTimeSource::new(value)
}
}
impl From<ManualTimeSource> for SharedTimeSource {
fn from(value: ManualTimeSource) -> Self {
SharedTimeSource::new(value)
}
}