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
56
57
58
59
60
use crate::utils::timeout_err;
use std::future::Future;
use std::io;
use std::pin::Pin;
use std::task::{Context, Poll};
use pin_project_lite::pin_project;
pin_project! {
#[must_use = "futures do nothing unless polled or .awaited"]
pub struct Timeout<F, D> {
#[pin]
future: F,
#[pin]
deadline: D,
completed: bool,
}
}
impl<F, D> Timeout<F, D> {
pub(super) fn new(future: F, deadline: D) -> Self {
Self {
future,
deadline,
completed: false,
}
}
}
impl<F: Future, D: Future> Future for Timeout<F, D> {
type Output = io::Result<F::Output>;
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
let this = self.project();
assert!(!*this.completed, "future polled after completing");
match this.future.poll(cx) {
Poll::Ready(v) => {
*this.completed = true;
Poll::Ready(Ok(v))
}
Poll::Pending => match this.deadline.poll(cx) {
Poll::Ready(_) => {
*this.completed = true;
Poll::Ready(Err(timeout_err("future timed out")))
}
Poll::Pending => Poll::Pending,
},
}
}
}