diff options
Diffstat (limited to 'embassy-time/src/timer.rs')
| -rw-r--r-- | embassy-time/src/timer.rs | 15 |
1 files changed, 14 insertions, 1 deletions
diff --git a/embassy-time/src/timer.rs b/embassy-time/src/timer.rs index 565a65cb8..dbce9297c 100644 --- a/embassy-time/src/timer.rs +++ b/embassy-time/src/timer.rs | |||
| @@ -8,7 +8,7 @@ use futures_util::{pin_mut, Stream}; | |||
| 8 | 8 | ||
| 9 | use crate::{Duration, Instant}; | 9 | use crate::{Duration, Instant}; |
| 10 | 10 | ||
| 11 | /// Error returned by [`with_timeout`] on timeout. | 11 | /// Error returned by [`with_timeout`] and [`timeout_at`] on timeout. |
| 12 | #[derive(Debug, Clone, PartialEq, Eq)] | 12 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 13 | #[cfg_attr(feature = "defmt", derive(defmt::Format))] | 13 | #[cfg_attr(feature = "defmt", derive(defmt::Format))] |
| 14 | pub struct TimeoutError; | 14 | pub struct TimeoutError; |
| @@ -26,6 +26,19 @@ pub async fn with_timeout<F: Future>(timeout: Duration, fut: F) -> Result<F::Out | |||
| 26 | } | 26 | } |
| 27 | } | 27 | } |
| 28 | 28 | ||
| 29 | /// Runs a given future with a deadline time. | ||
| 30 | /// | ||
| 31 | /// If the future completes before the deadline, its output is returned. Otherwise, on timeout, | ||
| 32 | /// work on the future is stopped (`poll` is no longer called), the future is dropped and `Err(TimeoutError)` is returned. | ||
| 33 | pub async fn timeout_at<F: Future>(at: Instant, fut: F) -> Result<F::Output, TimeoutError> { | ||
| 34 | let timeout_fut = Timer::at(at); | ||
| 35 | pin_mut!(fut); | ||
| 36 | match select(fut, timeout_fut).await { | ||
| 37 | Either::Left((r, _)) => Ok(r), | ||
| 38 | Either::Right(_) => Err(TimeoutError), | ||
| 39 | } | ||
| 40 | } | ||
| 41 | |||
| 29 | /// A future that completes at a specified [Instant](struct.Instant.html). | 42 | /// A future that completes at a specified [Instant](struct.Instant.html). |
| 30 | #[must_use = "futures do nothing unless you `.await` or poll them"] | 43 | #[must_use = "futures do nothing unless you `.await` or poll them"] |
| 31 | pub struct Timer { | 44 | pub struct Timer { |
