Skip to content
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

Adding timeout extension method to Future trait #600

Merged
merged 14 commits into from
Dec 20, 2019
35 changes: 35 additions & 0 deletions src/future/future/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ cfg_unstable! {
use try_race::TryRace;
use join::Join;
use try_join::TryJoin;
use crate::future::timeout::TimeoutFuture;
}

extension_trait! {
Expand Down Expand Up @@ -355,6 +356,40 @@ extension_trait! {
{
TryJoin::new(self, other)
}

#[doc = r#"
Waits for both the future and a timeout, if the timeout completes before
the future, it returns an TimeoutError.
k-nasa marked this conversation as resolved.
Show resolved Hide resolved

# Example
```
# async_std::task::block_on(async {
#
use std::time::Duration;

use async_std::prelude::*;
use async_std::future;

let fut = future::ready(0);
let dur = Duration::from_millis(100);
let res = fut.timeout(dur).await;
assert!(res.is_ok());

let fut = future::pending::<()>();
let dur = Duration::from_millis(100);
let res = fut.timeout(dur).await;
assert!(res.is_err())
#
# });
```
"#]
#[cfg(any(feature = "unstable", feature = "docs"))]
#[cfg_attr(feature = "docs", doc(cfg(unstable)))]
fn timeout(self, dur: Duration) -> impl Future<Output = Self::Output> [TimeoutFuture<Self>]
where Self: Sized
{
TimeoutFuture::new(self, dur)
}
}

impl<F: Future + Unpin + ?Sized> Future for Box<F> {
Expand Down
9 changes: 8 additions & 1 deletion src/future/timeout.rs
Original file line number Diff line number Diff line change
Expand Up @@ -42,14 +42,21 @@ where

pin_project! {
/// A future that times out after a duration of time.
struct TimeoutFuture<F> {
pub struct TimeoutFuture<F> {
#[pin]
future: F,
#[pin]
delay: Delay,
}
}

impl<F> TimeoutFuture<F> {
#[allow(dead_code)]
pub(super) fn new(future: F, dur: Duration) -> TimeoutFuture<F> {
TimeoutFuture { future: future, delay: Delay::new(dur) }
}
}

impl<F: Future> Future for TimeoutFuture<F> {
type Output = Result<F::Output, TimeoutError>;

Expand Down