diff options
| author | xoviat <[email protected]> | 2021-03-29 15:48:57 -0500 |
|---|---|---|
| committer | xoviat <[email protected]> | 2021-03-29 15:48:57 -0500 |
| commit | 49d87ac86862d89a178058ccd2acc23113b1f0d5 (patch) | |
| tree | c5e5bf758c849729f6a993a797a82c283a9a0bc8 | |
| parent | 86f59d144470c2611a8babd9a49f528502752181 (diff) | |
add with_timeout
| -rw-r--r-- | embassy/src/executor/timer.rs | 12 | ||||
| -rw-r--r-- | embassy/src/time/mod.rs | 2 |
2 files changed, 12 insertions, 2 deletions
diff --git a/embassy/src/executor/timer.rs b/embassy/src/executor/timer.rs index 774613ebf..8297564a0 100644 --- a/embassy/src/executor/timer.rs +++ b/embassy/src/executor/timer.rs | |||
| @@ -2,7 +2,7 @@ use core::future::Future; | |||
| 2 | use core::marker::PhantomData; | 2 | use core::marker::PhantomData; |
| 3 | use core::pin::Pin; | 3 | use core::pin::Pin; |
| 4 | use core::task::{Context, Poll}; | 4 | use core::task::{Context, Poll}; |
| 5 | use futures::Stream; | 5 | use futures::{future::select, future::Either, pin_mut, Stream}; |
| 6 | 6 | ||
| 7 | use super::raw; | 7 | use super::raw; |
| 8 | use crate::time::{Duration, Instant}; | 8 | use crate::time::{Duration, Instant}; |
| @@ -31,6 +31,16 @@ impl crate::traits::delay::Delay for Delay { | |||
| 31 | } | 31 | } |
| 32 | } | 32 | } |
| 33 | 33 | ||
| 34 | pub struct TimeoutError; | ||
| 35 | pub async fn with_timeout<F: Future>(timeout: Duration, fut: F) -> Result<F::Output, TimeoutError> { | ||
| 36 | let timeout_fut = Timer::after(timeout); | ||
| 37 | pin_mut!(fut); | ||
| 38 | match select(fut, timeout_fut).await { | ||
| 39 | Either::Left((r, _)) => Ok(r), | ||
| 40 | Either::Right(_) => Err(TimeoutError), | ||
| 41 | } | ||
| 42 | } | ||
| 43 | |||
| 34 | /// A future that completes at a specified [Instant](struct.Instant.html). | 44 | /// A future that completes at a specified [Instant](struct.Instant.html). |
| 35 | pub struct Timer { | 45 | pub struct Timer { |
| 36 | expires_at: Instant, | 46 | expires_at: Instant, |
diff --git a/embassy/src/time/mod.rs b/embassy/src/time/mod.rs index 4e9b5f592..d7284b7a2 100644 --- a/embassy/src/time/mod.rs +++ b/embassy/src/time/mod.rs | |||
| @@ -5,7 +5,7 @@ mod duration; | |||
| 5 | mod instant; | 5 | mod instant; |
| 6 | mod traits; | 6 | mod traits; |
| 7 | 7 | ||
| 8 | pub use crate::executor::timer::{Delay, Ticker, Timer}; | 8 | pub use crate::executor::timer::{with_timeout, Delay, Ticker, TimeoutError, Timer}; |
| 9 | pub use duration::Duration; | 9 | pub use duration::Duration; |
| 10 | pub use instant::Instant; | 10 | pub use instant::Instant; |
| 11 | pub use traits::*; | 11 | pub use traits::*; |
