use std::future::Future;
use std::pin::Pin;
use std::task::{Context, Poll};
use tokio::time::{Duration, Instant, Sleep, sleep};
pub struct EventTimer {
inner: Option<Pin<Box<Sleep>>>,
}
impl EventTimer {
pub fn new() -> Self {
Self { inner: None }
}
pub fn reset(&mut self, duration: Duration) {
match &mut self.inner {
Some(sleep) => sleep.as_mut().reset(Instant::now() + duration),
None => self.inner = Some(Box::pin(sleep(duration))),
}
}
pub fn stop(&mut self) {
self.inner = None;
}
}
impl Default for EventTimer {
fn default() -> Self {
Self::new()
}
}
impl Future for EventTimer {
type Output = ();
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<()> {
match &mut self.inner {
Some(sleep) => {
let result = sleep.as_mut().poll(cx);
if result.is_ready() {
self.inner = None;
}
result
}
None => Poll::Pending,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use tokio::time::Duration;
#[tokio::test]
async fn test_disarmed_never_fires() {
let mut timer = EventTimer::new();
tokio::select! {
() = &mut timer => panic!("disarmed timer should never fire"),
() = tokio::time::sleep(Duration::from_millis(50)) => {}
}
}
#[tokio::test]
async fn test_arm_and_fire() {
let mut timer = EventTimer::new();
timer.reset(Duration::from_millis(30));
tokio::select! {
() = &mut timer => {}
() = tokio::time::sleep(Duration::from_secs(1)) => panic!("timer should have fired"),
}
}
#[tokio::test]
async fn test_auto_disarm_after_fire() {
let mut timer = EventTimer::new();
timer.reset(Duration::from_millis(10));
tokio::time::sleep(Duration::from_millis(30)).await;
tokio::select! {
() = &mut timer => {}
() = tokio::time::sleep(Duration::from_millis(10)) => panic!("timer should have fired"),
}
tokio::select! {
() = &mut timer => panic!("timer should be disarmed after firing"),
() = tokio::time::sleep(Duration::from_millis(50)) => {}
}
}
#[tokio::test]
async fn test_reset_extends_deadline() {
let mut timer = EventTimer::new();
timer.reset(Duration::from_millis(50));
tokio::time::sleep(Duration::from_millis(20)).await;
timer.reset(Duration::from_millis(80));
tokio::select! {
() = &mut timer => panic!("timer fired too early after reset"),
() = tokio::time::sleep(Duration::from_millis(50)) => {}
}
tokio::select! {
() = &mut timer => {}
() = tokio::time::sleep(Duration::from_secs(1)) => panic!("timer should have fired"),
}
}
#[tokio::test]
async fn test_stop_disarms() {
let mut timer = EventTimer::new();
timer.reset(Duration::from_millis(30));
timer.stop();
tokio::select! {
() = &mut timer => panic!("stopped timer should not fire"),
() = tokio::time::sleep(Duration::from_millis(100)) => {}
}
}
#[tokio::test]
async fn test_stop_then_reset() {
let mut timer = EventTimer::new();
timer.reset(Duration::from_millis(50));
timer.stop();
timer.reset(Duration::from_millis(30));
tokio::select! {
() = &mut timer => {}
() = tokio::time::sleep(Duration::from_secs(1)) => panic!("re-armed timer should fire"),
}
}
}