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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
use std::pin::Pin;
use std::task::{Context, Poll};
use std::time::Duration;
use futures_timer::Delay;
use pin_utils::unsafe_pinned;
use crate::future::Future;
use crate::io;
pub async fn timeout<F, T>(dur: Duration, f: F) -> io::Result<T>
where
F: Future<Output = io::Result<T>>,
{
Timeout {
timeout: Delay::new(dur),
future: f,
}
.await
}
#[derive(Debug)]
pub struct Timeout<F, T>
where
F: Future<Output = io::Result<T>>,
{
future: F,
timeout: Delay,
}
impl<F, T> Timeout<F, T>
where
F: Future<Output = io::Result<T>>,
{
unsafe_pinned!(future: F);
unsafe_pinned!(timeout: Delay);
}
impl<F, T> Future for Timeout<F, T>
where
F: Future<Output = io::Result<T>>,
{
type Output = io::Result<T>;
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
match self.as_mut().future().poll(cx) {
Poll::Pending => {}
other => return other,
}
if self.timeout().poll(cx).is_ready() {
let err = Err(io::Error::new(io::ErrorKind::TimedOut, "future timed out").into());
Poll::Ready(err)
} else {
Poll::Pending
}
}
}