use crate::time::{Duration, Instant};
#[derive(Clone, Copy, Debug)]
pub(crate) struct Watchdog {
limit: Duration,
deadline: Option<Instant>,
}
impl Watchdog {
pub(crate) fn new(now: Instant, first: Duration, limit: Duration) -> Self {
Watchdog {
limit,
deadline: now.checked_add(first),
}
}
pub(crate) fn progress(&mut self, now: Instant) {
self.deadline = now.checked_add(self.limit);
}
pub(crate) fn deadline(&self) -> Option<Instant> {
self.deadline
}
pub(crate) fn expired(&self, now: Instant) -> bool {
self.deadline.is_some_and(|d| now >= d)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn progress_moves_the_deadline_and_silence_expires_it() {
let t0 = Instant::now();
let s = Duration::from_secs(1);
let mut w = Watchdog::new(t0, 3 * s, 2 * s);
assert_eq!(w.deadline(), Some(t0 + 3 * s));
assert!(!w.expired(t0 + 2 * s));
for i in 1..100 {
let now = t0 + i * s;
assert!(!w.expired(now));
w.progress(now);
}
let last = t0 + 99 * s;
assert_eq!(w.deadline(), Some(last + 2 * s));
assert!(!w.expired(last + 2 * s - Duration::from_millis(1)));
assert!(w.expired(last + 2 * s));
}
#[test]
fn a_limit_beyond_the_clock_never_expires() {
let t0 = Instant::now();
let w = Watchdog::new(t0, Duration::MAX, Duration::MAX);
assert_eq!(w.deadline(), None);
assert!(!w.expired(t0 + Duration::from_secs(1 << 20)));
}
}