File tree 2 files changed +43
-1
lines changed
2 files changed +43
-1
lines changed Original file line number Diff line number Diff line change @@ -15,6 +15,7 @@ cfg_unstable! {
15
15
use try_race:: TryRace ;
16
16
use join:: Join ;
17
17
use try_join:: TryJoin ;
18
+ use crate :: future:: timeout:: TimeoutFuture ;
18
19
}
19
20
20
21
extension_trait ! {
@@ -355,6 +356,40 @@ extension_trait! {
355
356
{
356
357
TryJoin :: new( self , other)
357
358
}
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
+ }
358
393
}
359
394
360
395
impl <F : Future + Unpin + ?Sized > Future for Box <F > {
Original file line number Diff line number Diff line change @@ -42,14 +42,21 @@ where
42
42
43
43
pin_project ! {
44
44
/// A future that times out after a duration of time.
45
- struct TimeoutFuture <F > {
45
+ pub struct TimeoutFuture <F > {
46
46
#[ pin]
47
47
future: F ,
48
48
#[ pin]
49
49
delay: Delay ,
50
50
}
51
51
}
52
52
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
+
53
60
impl < F : Future > Future for TimeoutFuture < F > {
54
61
type Output = Result < F :: Output , TimeoutError > ;
55
62
You can’t perform that action at this time.
0 commit comments