use std::future::Future;
use std::future::IntoFuture;
use std::task::Context;
use std::task::Poll;
use std::time::Duration;
use std::time::Instant;
use crate::MakeDelay;
#[derive(Debug, PartialEq, Eq)]
pub struct Elapsed(());
#[must_use = "futures do nothing unless you `.await` or poll them"]
#[derive(Debug)]
#[pin_project::pin_project]
pub struct Timeout<T, D> {
#[pin]
value: T,
#[pin]
delay: D,
}
impl<T, D> Timeout<T, D> {
pub fn get(&self) -> &T {
&self.value
}
pub fn get_mut(&mut self) -> &mut T {
&mut self.value
}
pub fn into_inner(self) -> T {
self.value
}
}
impl<T, D> Future for Timeout<T, D>
where
T: Future,
D: Future<Output = ()>,
{
type Output = Result<T::Output, Elapsed>;
fn poll(self: std::pin::Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
let this = self.project();
if let Poll::Ready(v) = this.value.poll(cx) {
return Poll::Ready(Ok(v));
}
match this.delay.poll(cx) {
Poll::Ready(()) => Poll::Ready(Err(Elapsed(()))),
Poll::Pending => Poll::Pending,
}
}
}
pub fn timeout<F, D>(
duration: Duration,
future: F,
make_delay: &D,
) -> Timeout<F::IntoFuture, D::Delay>
where
F: IntoFuture,
D: MakeDelay + ?Sized,
{
let delay = make_delay.delay(duration);
Timeout {
value: future.into_future(),
delay,
}
}
pub fn timeout_at<F, D>(
deadline: Instant,
future: F,
make_delay: &D,
) -> Timeout<F::IntoFuture, D::Delay>
where
F: IntoFuture,
D: MakeDelay + ?Sized,
{
let delay = make_delay.delay_until(deadline);
Timeout {
value: future.into_future(),
delay,
}
}