use core::num::NonZeroUsize;
use instant::Instant;
use std::time::Duration;
#[derive(Debug, Clone)]
pub struct Timer {
period: Duration,
init: Instant,
}
impl Timer {
pub fn time_per_second(times: f32) -> Timer {
Timer::with_duration(Duration::from_secs_f32(1.0 / times))
}
pub fn with_duration(period: Duration) -> Timer {
Timer {
period,
init: Instant::now(),
}
}
pub fn tick(&mut self) -> bool {
if self.init.elapsed() >= self.period {
self.init += self.period;
true
} else {
false
}
}
pub fn exhaust(&mut self) -> Option<NonZeroUsize> {
let mut count = 0;
while self.tick() {
count += 1;
}
NonZeroUsize::new(count)
}
pub fn reset(&mut self) {
self.init = Instant::now();
}
pub fn period(&self) -> Duration {
self.period
}
pub fn elapsed(&self) -> Duration {
self.init.elapsed()
}
pub fn remaining(&self) -> Option<Duration> {
self.period.checked_sub(self.init.elapsed())
}
pub fn late_by(&self) -> Option<Duration> {
self.init.elapsed().checked_sub(self.period)
}
}