diff --git a/src/future/future/mod.rs b/src/future/future/mod.rs index 3be9343..e302175 100644 --- a/src/future/future/mod.rs +++ b/src/future/future/mod.rs @@ -360,10 +360,25 @@ extension_trait! { #[doc = r#" Waits for both the future and a timeout, if the timeout completes before the future, it returns an TimeoutError. + + # Example + ``` + #async_std::task::block_on(async { + let fut = future::ready(0); + let dur = Duration::from_millis(100); + let res = fut.timeout(dur).await; + assert!(res.is_ok()); + + let fut = future::ready(0); + let dur = Duration::from_millis(100); + let res = fut.timeout(dur).await; + assert!(res.is_ok()) + # }); + ``` "#] #[cfg(any(feature = "unstable", feature = "docs"))] #[cfg_attr(feature = "docs", doc(cfg(unstable)))] - fn timeout(self, dur: Duration) -> impl Future [TimeoutFuture] + fn timeout(self, dur: Duration) -> impl Future [TimeoutFuture] where Self: Sized { TimeoutFuture::new(self, dur) diff --git a/src/future/timeout.rs b/src/future/timeout.rs index c2b6306..05aaa45 100644 --- a/src/future/timeout.rs +++ b/src/future/timeout.rs @@ -51,7 +51,8 @@ pin_project! { } impl TimeoutFuture { - pub fn new(future: F, dur: Duration) -> TimeoutFuture { + #[allow(dead_code)] + pub(super) fn new(future: F, dur: Duration) -> TimeoutFuture { TimeoutFuture { future: future, delay: Delay::new(dur) } } } diff --git a/tests/timeout_future.rs b/tests/timeout_future.rs new file mode 100644 index 0000000..e6e4b34 --- /dev/null +++ b/tests/timeout_future.rs @@ -0,0 +1,27 @@ +#![cfg(feature = "unstable")] + +use std::time::Duration; + +use async_std::future; +use async_std::prelude::*; +use async_std::task; + +#[test] +fn should_timeout() { + task::block_on(async { + let fut = future::pending::<()>(); + let dur = Duration::from_millis(100); + let res = fut.timeout(dur).await; + assert!(res.is_err()); + }); +} + +#[test] +fn should_not_timeout() { + task::block_on(async { + let fut = future::ready(0); + let dur = Duration::from_millis(100); + let res = fut.timeout(dur).await; + assert!(res.is_ok()); + }); +}