use super::Driver;
use std::pin::Pin;
use std::task::{Context, Poll};
use std::time::Duration;
use tokio::time::Sleep;
pub(crate) struct TokioDriver {
sleep: Pin<Box<Sleep>>,
armed: Option<Duration>,
}
impl TokioDriver {
pub(crate) fn new() -> Self {
Self { sleep: Box::pin(tokio::time::sleep(Duration::ZERO)), armed: None }
}
}
impl Driver for TokioDriver {
fn wait(
&mut self,
deadline: Option<Duration>,
now: Duration,
cx: &mut Context<'_>,
) -> Poll<()> {
if self.armed != deadline || self.sleep.is_elapsed() {
self.armed = deadline;
match deadline {
Some(at) => {
let wait = at.saturating_sub(now);
self.sleep.as_mut().reset(tokio::time::Instant::now() + wait);
}
None => return Poll::Pending,
}
}
if self.armed.is_none() {
return Poll::Pending;
}
self.sleep.as_mut().poll(cx)
}
}