rust-embedded / embedded-hal

A Hardware Abstraction Layer (HAL) for embedded systems
Apache License 2.0
2.01k stars 202 forks source link

Add `timeout_{us, ms}` to `embedded_hal_async::DelayUs` #452

Open datdenkikniet opened 1 year ago

datdenkikniet commented 1 year ago

Use cases where one wishes to select between a DelayUs::delay_us and a different Future are likely to be quite common.

I propose that we add something like async fn timeout_{us, ms}<F: Future>(timeout: u32, f: F) -> Result<F::Output, TimeoutError> to the DelayUs trait, with a default impl that falls back to a futures::select between self.timeout_{us, ms}() and f.

Dirbaio commented 1 year ago

You can already do it now with delay_[mu]s and select (there's select available in several crates, for example embassy-futures or futures).

I'm not sure if we should add this as a convenience method, because the generics could prevent the trait to become dyn-safe. (currently async traits are never dyn-safe, but there's work in progress in Rust to allow some async traits to be, and when that happens it's likely it'll have the same restrictions as non-async traits. in particular, traits with methods with generics can't be dyn-safe.)