From c1f7be5d42f9fbeb63250e2b4f75986d2ae94fec Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Miguel=20P=C3=A9rez=20Garc=C3=ADa?= Date: Sat, 23 Nov 2019 11:40:07 -0600 Subject: [PATCH] Adding timeout extension method to Future trait --- src/future/future/mod.rs | 13 +++++++++++++ src/future/timeout.rs | 8 +++++++- 2 files changed, 20 insertions(+), 1 deletion(-) diff --git a/src/future/future/mod.rs b/src/future/future/mod.rs index 5fdaf4b..fc800cb 100644 --- a/src/future/future/mod.rs +++ b/src/future/future/mod.rs @@ -15,6 +15,7 @@ cfg_unstable! { use try_race::TryRace; use join::Join; use try_join::TryJoin; + use crate::future::timeout::TimeoutFuture; } extension_trait! { @@ -355,6 +356,18 @@ 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. + "#] + #[cfg(any(feature = "unstable", feature = "docs"))] + #[cfg_attr(feature = "docs", doc(cfg(unstable)))] + fn timeout(self, dur: Duration) -> impl Future [TimeoutFuture] + where Self: Sized + { + TimeoutFuture::new(self, dur) + } } impl Future for Box { diff --git a/src/future/timeout.rs b/src/future/timeout.rs index ff87ae4..c2b6306 100644 --- a/src/future/timeout.rs +++ b/src/future/timeout.rs @@ -42,7 +42,7 @@ where pin_project! { /// A future that times out after a duration of time. - struct TimeoutFuture { + pub struct TimeoutFuture { #[pin] future: F, #[pin] @@ -50,6 +50,12 @@ pin_project! { } } +impl TimeoutFuture { + pub fn new(future: F, dur: Duration) -> TimeoutFuture { + TimeoutFuture { future: future, delay: Delay::new(dur) } + } +} + impl Future for TimeoutFuture { type Output = Result;