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; use core::marker::PhantomData; use core::pin::Pin; use core::task::{Context, Poll}; -use futures::Stream; +use futures::{future::select, future::Either, pin_mut, Stream}; use super::raw; use crate::time::{Duration, Instant}; @@ -31,6 +31,16 @@ impl crate::traits::delay::Delay for Delay { } } +pub struct TimeoutError; +pub async fn with_timeout(timeout: Duration, fut: F) -> Result { + let timeout_fut = Timer::after(timeout); + 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). pub struct Timer { 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; mod instant; mod traits; -pub use crate::executor::timer::{Delay, Ticker, Timer}; +pub use crate::executor::timer::{with_timeout, Delay, Ticker, TimeoutError, Timer}; pub use duration::Duration; pub use instant::Instant; pub use traits::*;