Skip to content

Commit c1f7be5

Browse files
committed
Adding timeout extension method to Future trait
1 parent 50cefce commit c1f7be5

File tree

2 files changed

+20
-1
lines changed

2 files changed

+20
-1
lines changed

src/future/future/mod.rs

+13
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@ cfg_unstable! {
1515
use try_race::TryRace;
1616
use join::Join;
1717
use try_join::TryJoin;
18+
use crate::future::timeout::TimeoutFuture;
1819
}
1920

2021
extension_trait! {
@@ -355,6 +356,18 @@ extension_trait! {
355356
{
356357
TryJoin::new(self, other)
357358
}
359+
360+
#[doc = r#"
361+
Waits for both the future and a timeout, if the timeout completes before
362+
the future, it returns an TimeoutError.
363+
"#]
364+
#[cfg(any(feature = "unstable", feature = "docs"))]
365+
#[cfg_attr(feature = "docs", doc(cfg(unstable)))]
366+
fn timeout<F, T>(self, dur: Duration) -> impl Future<Output = Self::Output> [TimeoutFuture<Self>]
367+
where Self: Sized
368+
{
369+
TimeoutFuture::new(self, dur)
370+
}
358371
}
359372

360373
impl<F: Future + Unpin + ?Sized> Future for Box<F> {

src/future/timeout.rs

+7-1
Original file line numberDiff line numberDiff line change
@@ -42,14 +42,20 @@ where
4242

4343
pin_project! {
4444
/// A future that times out after a duration of time.
45-
struct TimeoutFuture<F> {
45+
pub struct TimeoutFuture<F> {
4646
#[pin]
4747
future: F,
4848
#[pin]
4949
delay: Delay,
5050
}
5151
}
5252

53+
impl<F> TimeoutFuture<F> {
54+
pub fn new(future: F, dur: Duration) -> TimeoutFuture<F> {
55+
TimeoutFuture { future: future, delay: Delay::new(dur) }
56+
}
57+
}
58+
5359
impl<F: Future> Future for TimeoutFuture<F> {
5460
type Output = Result<F::Output, TimeoutError>;
5561

0 commit comments

Comments
 (0)