use std::time::{Duration, Instant};
#[derive(Copy, Clone, Debug)]
pub struct Timer {
length: Duration,
end: Instant,
}
impl Timer {
pub fn start(length: Duration) -> Self {
Self {
length,
end: clock::now() + length,
}
}
pub fn is_expired(&self) -> bool {
self.end <= clock::now()
}
pub fn postpone(&mut self, other: &Self) {
assert!(self.length == other.length);
if other.end > self.end {
self.end = other.end
}
}
pub fn restart(&mut self) {
self.end = clock::now() + self.length
}
}
#[cfg(not(test))]
mod clock {
use std::time::Instant;
pub fn now() -> Instant {
Instant::now()
}
}
#[cfg(test)]
pub mod clock {
use lazy_static::lazy_static;
use std::{
sync::Mutex,
time::{Duration, Instant},
};
lazy_static! {
static ref EPOCH: Instant = Instant::now();
static ref DELTA: Mutex<Duration> = Mutex::new(Duration::ZERO);
}
pub fn now() -> Instant {
let delta = DELTA.lock().unwrap();
*EPOCH + *delta
}
pub fn tick() {
advance(Duration::SECOND)
}
pub fn advance(duration: Duration) {
let mut delta = DELTA.lock().unwrap();
*delta += duration;
if delta.as_secs() % 60 == 0 {
println!(" * * * TIME {:?} * * * ", *delta)
}
}
}