Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 0d4b4cd

Browse files
authored
Merge pull request #600 from miker1423/future-timeout
Adding timeout extension method to Future trait
2 parents d2c25f4 + ef021dc commit 0d4b4cd

File tree

2 files changed

+43
-1
lines changed

2 files changed

+43
-1
lines changed

‎src/future/future/mod.rs‎

Lines changed: 35 additions & 0 deletions
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,40 @@ 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+
# Example
365+
```
366+
# async_std::task::block_on(async {
367+
#
368+
use std::time::Duration;
369+
370+
use async_std::prelude::*;
371+
use async_std::future;
372+
373+
let fut = future::ready(0);
374+
let dur = Duration::from_millis(100);
375+
let res = fut.timeout(dur).await;
376+
assert!(res.is_ok());
377+
378+
let fut = future::pending::<()>();
379+
let dur = Duration::from_millis(100);
380+
let res = fut.timeout(dur).await;
381+
assert!(res.is_err())
382+
#
383+
# });
384+
```
385+
"#]
386+
#[cfg(any(feature = "unstable", feature = "docs"))]
387+
#[cfg_attr(feature = "docs", doc(cfg(unstable)))]
388+
fn timeout(self, dur: Duration) -> impl Future<Output = Self::Output> [TimeoutFuture<Self>]
389+
where Self: Sized
390+
{
391+
TimeoutFuture::new(self, dur)
392+
}
358393
}
359394

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

‎src/future/timeout.rs‎

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -42,14 +42,21 @@ where
4242

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

53+
impl<F> TimeoutFuture<F> {
54+
#[allow(dead_code)]
55+
pub(super) fn new(future: F, dur: Duration) -> TimeoutFuture<F> {
56+
TimeoutFuture { future: future, delay: Delay::new(dur) }
57+
}
58+
}
59+
5360
impl<F: Future> Future for TimeoutFuture<F> {
5461
type Output = Result<F::Output, TimeoutError>;
5562

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /