File tree Expand file tree Collapse file tree 2 files changed +43
-1
lines changed Expand file tree Collapse file tree 2 files changed +43
-1
lines changed Original file line number Diff line number Diff 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
2021extension_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 > {
Original file line number Diff line number Diff line change @@ -42,14 +42,21 @@ where
4242
4343pin_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+ #[ 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+
5360impl < F : Future > Future for TimeoutFuture < F > {
5461 type Output = Result < F :: Output , TimeoutError > ;
5562
You can’t perform that action at this time.
0 commit comments