Inline TryFutureExt logic for src/io/timeout.rs (#317)

yoshuawuyts-patch-1
Wouter Geraedts 5 years ago committed by Stjepan Glavina
parent 1819408b46
commit c7f6543502

@ -1,6 +1,9 @@
use std::pin::Pin;
use std::task::{Context, Poll};
use std::time::Duration;
use futures_timer::TryFutureExt;
use futures_core::future::TryFuture;
use futures_timer::Delay;
use crate::future::Future;
use crate::io;
@ -33,5 +36,48 @@ pub async fn timeout<F, T>(dur: Duration, f: F) -> io::Result<T>
where
F: Future<Output = io::Result<T>>,
{
f.timeout(dur).await
let f = TimeoutFuture {
timeout: Delay::new(dur),
future: f,
};
f.await
}
// Future returned by the [`io::timeout`](./fn.timeout.html) function.
#[derive(Debug)]
pub struct TimeoutFuture<F, T>
where
F: Future<Output = io::Result<T>>,
{
future: F,
timeout: Delay,
}
impl<F, T> TimeoutFuture<F, T>
where
F: Future<Output = io::Result<T>>,
{
pin_utils::unsafe_pinned!(future: F);
pin_utils::unsafe_pinned!(timeout: Delay);
}
impl<F, T> Future for TimeoutFuture<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().try_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
}
}
}

Loading…
Cancel
Save