Skip to content

Commit c7f6543

Browse files
WassasinStjepan Glavina
authored and
Stjepan Glavina
committed
Inline TryFutureExt logic for src/io/timeout.rs (#317)
1 parent 1819408 commit c7f6543

File tree

1 file changed

+48
-2
lines changed

1 file changed

+48
-2
lines changed

src/io/timeout.rs

+48-2
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,9 @@
1+
use std::pin::Pin;
2+
use std::task::{Context, Poll};
13
use std::time::Duration;
24

3-
use futures_timer::TryFutureExt;
5+
use futures_core::future::TryFuture;
6+
use futures_timer::Delay;
47

58
use crate::future::Future;
69
use crate::io;
@@ -33,5 +36,48 @@ pub async fn timeout<F, T>(dur: Duration, f: F) -> io::Result<T>
3336
where
3437
F: Future<Output = io::Result<T>>,
3538
{
36-
f.timeout(dur).await
39+
let f = TimeoutFuture {
40+
timeout: Delay::new(dur),
41+
future: f,
42+
};
43+
f.await
44+
}
45+
46+
// Future returned by the [`io::timeout`](./fn.timeout.html) function.
47+
#[derive(Debug)]
48+
pub struct TimeoutFuture<F, T>
49+
where
50+
F: Future<Output = io::Result<T>>,
51+
{
52+
future: F,
53+
timeout: Delay,
54+
}
55+
56+
impl<F, T> TimeoutFuture<F, T>
57+
where
58+
F: Future<Output = io::Result<T>>,
59+
{
60+
pin_utils::unsafe_pinned!(future: F);
61+
pin_utils::unsafe_pinned!(timeout: Delay);
62+
}
63+
64+
impl<F, T> Future for TimeoutFuture<F, T>
65+
where
66+
F: Future<Output = io::Result<T>>,
67+
{
68+
type Output = io::Result<T>;
69+
70+
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
71+
match self.as_mut().future().try_poll(cx) {
72+
Poll::Pending => {}
73+
other => return other,
74+
}
75+
76+
if self.timeout().poll(cx).is_ready() {
77+
let err = Err(io::Error::new(io::ErrorKind::TimedOut, "future timed out").into());
78+
Poll::Ready(err)
79+
} else {
80+
Poll::Pending
81+
}
82+
}
3783
}

0 commit comments

Comments
 (0)