Skip to content

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

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
1 commit merged into from
Oct 15, 2019
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
50 changes: 48 additions & 2 deletions src/io/timeout.rs
Original file line number Diff line number Diff line change
@@ -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;
Expand Down Expand Up @@ -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
}
}
}