From 1e698af05bc6e7e520d3f35ef661f34ea6ea359e Mon Sep 17 00:00:00 2001 From: Caleb Jamison Date: Wed, 31 Jan 2024 14:04:48 -0500 Subject: Add timeout_at convenience function and example. --- embassy-time/src/lib.rs | 2 +- embassy-time/src/timer.rs | 15 ++++++++++++++- 2 files changed, 15 insertions(+), 2 deletions(-) (limited to 'embassy-time/src') diff --git a/embassy-time/src/lib.rs b/embassy-time/src/lib.rs index d27eb92f6..e7efce49c 100644 --- a/embassy-time/src/lib.rs +++ b/embassy-time/src/lib.rs @@ -32,7 +32,7 @@ pub use delay::{block_for, Delay}; pub use duration::Duration; pub use embassy_time_driver::TICK_HZ; pub use instant::Instant; -pub use timer::{with_timeout, Ticker, TimeoutError, Timer}; +pub use timer::{timeout_at, with_timeout, Ticker, TimeoutError, Timer}; const fn gcd(a: u64, b: u64) -> u64 { if b == 0 { 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}; use crate::{Duration, Instant}; -/// Error returned by [`with_timeout`] on timeout. +/// Error returned by [`with_timeout`] and [`timeout_at`] on timeout. #[derive(Debug, Clone, PartialEq, Eq)] #[cfg_attr(feature = "defmt", derive(defmt::Format))] pub struct TimeoutError; @@ -26,6 +26,19 @@ pub async fn with_timeout(timeout: Duration, fut: F) -> Result(at: Instant, fut: F) -> Result { + let timeout_fut = Timer::at(at); + pin_mut!(fut); + match select(fut, timeout_fut).await { + Either::Left((r, _)) => Ok(r), + Either::Right(_) => Err(TimeoutError), + } +} + /// A future that completes at a specified [Instant](struct.Instant.html). #[must_use = "futures do nothing unless you `.await` or poll them"] pub struct Timer { -- cgit