1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
use crate::Sleep;
use futures::future::Future;
use pin_project::pin_project;
use std::{
pin::Pin,
task::{Context, Poll},
};
use thiserror::Error;
#[derive(Debug, Error, Eq, PartialEq)]
#[error("timeout elapsed")]
pub struct Elapsed;
#[pin_project]
#[must_use = "futures do nothing unless you `.await` or poll them"]
pub struct Timeout<F> {
#[pin]
future: F,
#[pin]
delay: Sleep,
}
impl<F> Timeout<F> {
pub fn new(future: F, delay: Sleep) -> Self {
Self { future, delay }
}
pub fn into_inner(self) -> F {
self.future
}
}
impl<F: Future> Future for Timeout<F> {
type Output = Result<F::Output, Elapsed>;
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
let this = self.project();
if let Poll::Ready(v) = this.future.poll(cx) {
return Poll::Ready(Ok(v));
}
this.delay.poll(cx).map(|_| Err(Elapsed))
}
}