|
| 1 | +use std::pin::Pin; |
| 2 | +use std::task::{Context, Poll}; |
1 | 3 | use std::time::Duration;
|
2 | 4 |
|
3 |
| -use futures_timer::TryFutureExt; |
| 5 | +use futures_core::future::TryFuture; |
| 6 | +use futures_timer::Delay; |
4 | 7 |
|
5 | 8 | use crate::future::Future;
|
6 | 9 | use crate::io;
|
@@ -33,5 +36,48 @@ pub async fn timeout<F, T>(dur: Duration, f: F) -> io::Result<T>
|
33 | 36 | where
|
34 | 37 | F: Future<Output = io::Result<T>>,
|
35 | 38 | {
|
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 | + } |
37 | 83 | }
|
0 commit comments