use crate::*;
pub struct Timer<'a> {
state: &'a mut TimerState,
now: Duration,
}
impl Timer<'_> {
pub fn count(&self) -> u64 {
self.state.count
}
pub fn fired(&self) -> bool {
self.state.fired
}
pub fn reset(&mut self) {
self.state.start = self.now;
self.state.count = 0;
self.state.fired = false;
}
}
pub struct TimerState {
pub call: Call,
pub seen: bool,
start: Duration,
period: Duration,
repeat: bool,
count: u64,
fired: bool,
}
impl TimerState {
pub fn update(timers: &mut Vec<Self>, mut call: Call, period: Duration, repeat: bool, now: Duration) -> Timer<'_> {
let index = loop {
match timers.binary_search_by_key(&call, |timer| timer.call) {
Ok(index) if timers[index].seen => call.repeat += 1,
Ok(index) => break index,
Err(index) => {
timers.insert(index, Self::new(call, period, repeat, now));
break index;
}
}
};
let timer = &mut timers[index];
timer.seen = true;
if timer.period != period || timer.repeat != repeat {
*timer = Self {
seen: true,
..Self::new(call, period, repeat, now)
};
}
let elapsed = now.saturating_sub(timer.start).as_nanos();
let count = match period.as_nanos() {
0 => 1,
period => (elapsed / period).min(u64::MAX as u128) as u64,
};
let count = if repeat { count } else { count.min(1) };
timer.fired = count > timer.count;
timer.count = count;
Timer { state: timer, now }
}
pub fn deadline(&self) -> Option<Duration> {
if !self.repeat && self.count != 0 {
return None;
}
let next = self.period.as_nanos().saturating_mul(u128::from(self.count) + 1);
Some(
self.start
.saturating_add(Duration::from_nanos(next.min(u64::MAX as u128) as u64)),
)
}
}
impl TimerState {
fn new(call: Call, period: Duration, repeat: bool, now: Duration) -> Self {
Self {
call,
seen: false,
start: now,
period,
repeat,
count: 0,
fired: false,
}
}
}