Skip to content

Reduce io::TimeoutFuture to futures_timer::TryFutureExt #113

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
Aug 27, 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
41 changes: 2 additions & 39 deletions src/io/timeout.rs
Original file line number Diff line number Diff line change
@@ -1,12 +1,9 @@
use std::pin::Pin;
use std::time::Duration;

use futures_timer::Delay;
use pin_utils::unsafe_pinned;
use futures_timer::TryFutureExt;

use crate::future::Future;
use crate::io;
use crate::task::{Context, Poll};

/// Awaits an I/O future or times out after a duration of time.
///
Expand All @@ -33,39 +30,5 @@ pub async fn timeout<F, T>(dur: Duration, f: F) -> io::Result<T>
where
F: Future<Output = io::Result<T>>,
{
let f = TimeoutFuture {
future: f,
delay: Delay::new(dur),
};
f.await
}

struct TimeoutFuture<F> {
future: F,
delay: Delay,
}

impl<F> TimeoutFuture<F> {
unsafe_pinned!(future: F);
unsafe_pinned!(delay: Delay);
}

impl<F, T> Future for TimeoutFuture<F>
where
F: Future<Output = io::Result<T>>,
{
type Output = F::Output;

fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
match self.as_mut().future().poll(cx) {
Poll::Ready(v) => Poll::Ready(v),
Poll::Pending => match self.delay().poll(cx) {
Poll::Ready(_) => Poll::Ready(Err(io::Error::new(
io::ErrorKind::TimedOut,
"I/O operation has timed out",
))),
Poll::Pending => Poll::Pending,
},
}
}
f.timeout(dur).await
}