use std::{
fmt,
future::Future,
pin::Pin,
sync::{Arc, Mutex, PoisonError},
time::{Duration, Instant},
};
pub type Sleep = Pin<Box<dyn Future<Output = ()> + Send + 'static>>;
type Start = dyn Fn(Instant) -> Sleep + Send + Sync;
#[derive(Clone)]
pub struct Timer {
start: Arc<Start>,
}
impl Timer {
#[must_use]
pub fn new<F, S>(start: F) -> Self
where
F: Fn(Instant) -> S + Send + Sync + 'static,
S: Future<Output = ()> + Send + 'static,
{
Self {
start: Arc::new(move |deadline| Box::pin(start(deadline))),
}
}
pub(crate) fn until(&self, deadline: Instant) -> Sleep {
(self.start)(deadline)
}
pub(crate) fn after(&self, duration: Duration) -> Sleep {
let Some(deadline) = Instant::now().checked_add(duration) else {
return Box::pin(std::future::pending());
};
self.until(deadline)
}
}
impl Default for Timer {
fn default() -> Self {
Self::new(|deadline| async move {
let _ = async_io::Timer::at(deadline).await;
})
}
}
impl fmt::Debug for Timer {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.debug_struct("Timer").finish_non_exhaustive()
}
}
impl hyper::rt::Timer for Timer {
fn sleep(&self, duration: Duration) -> Pin<Box<dyn hyper::rt::Sleep>> {
Box::pin(HyperSleep(Mutex::new(self.after(duration))))
}
fn sleep_until(&self, deadline: Instant) -> Pin<Box<dyn hyper::rt::Sleep>> {
Box::pin(HyperSleep(Mutex::new(self.until(deadline))))
}
}
struct HyperSleep(Mutex<Sleep>);
impl Future for HyperSleep {
type Output = ();
fn poll(
self: Pin<&mut Self>,
context: &mut std::task::Context<'_>,
) -> std::task::Poll<Self::Output> {
self.0
.lock()
.unwrap_or_else(PoisonError::into_inner)
.as_mut()
.poll(context)
}
}
impl hyper::rt::Sleep for HyperSleep {}
#[cfg(test)]
mod tests {
use std::task::{Context, Poll, Waker};
use super::*;
#[test]
fn durations_beyond_the_platform_clock_wait_indefinitely() {
let mut sleep = Timer::default().after(Duration::MAX);
let mut context = Context::from_waker(Waker::noop());
assert!(matches!(sleep.as_mut().poll(&mut context), Poll::Pending));
}
}