From 1582dbc28baeac3ff08ca35444a0bbbd44c24d4b Mon Sep 17 00:00:00 2001 From: wackazong Date: Thu, 26 Dec 2024 05:20:17 +0100 Subject: [PATCH] feat: Add embassy-based sleeper for no_std (#173) --- backon/Cargo.toml | 2 ++ backon/src/embassy_timer_sleep.rs | 20 ++++++++++++++++++++ backon/src/lib.rs | 6 ++++++ 3 files changed, 28 insertions(+) create mode 100644 backon/src/embassy_timer_sleep.rs diff --git a/backon/Cargo.toml b/backon/Cargo.toml index d6bd83e..8ef5d53 100644 --- a/backon/Cargo.toml +++ b/backon/Cargo.toml @@ -25,9 +25,11 @@ std = ["fastrand/std"] std-blocking-sleep = [] gloo-timers-sleep = ["gloo-timers/futures"] tokio-sleep = ["tokio/time"] +embassy-sleep = ["embassy-time"] [dependencies] fastrand = { version = "2", default-features = false } +embassy-time = { version = "0.3", optional = true } [target.'cfg(not(target_arch = "wasm32"))'.dependencies] tokio = { version = "1", optional = true } diff --git a/backon/src/embassy_timer_sleep.rs b/backon/src/embassy_timer_sleep.rs new file mode 100644 index 0000000..749bcff --- /dev/null +++ b/backon/src/embassy_timer_sleep.rs @@ -0,0 +1,20 @@ +use crate::{BlockingSleeper, Sleeper}; +use core::time::Duration; + +/// A no_std async sleeper based on the embassy framework (https://embassy.dev) +#[derive(Clone, Copy, Debug, Default)] +pub struct EmbassySleeper; + +impl Sleeper for EmbassySleeper { + type Sleep = embassy_time::Timer; + + fn sleep(&self, dur: Duration) -> Self::Sleep { + embassy_time::Timer::after_millis(dur.as_millis() as u64) + } +} + +impl BlockingSleeper for EmbassySleeper { + fn sleep(&self, dur: Duration) { + embassy_time::block_for(embassy_time::Duration::from_millis(dur.as_millis() as u64)); + } +} diff --git a/backon/src/lib.rs b/backon/src/lib.rs index d6e4366..76b9c1c 100644 --- a/backon/src/lib.rs +++ b/backon/src/lib.rs @@ -45,6 +45,7 @@ //! |---------------------|--------------------|-------------|---------------| //! | [`TokioSleeper`] | tokio-sleep | non-wasm32 | Yes | //! | [`GlooTimersSleep`] | gloo-timers-sleep | wasm32 | Yes | +//! | [`EmbassySleep`] | embassy-sleep | no_std | Yes | //! | [`StdSleeper`] | std-blocking-sleep | std | No | //! //! ## Custom Sleeper @@ -184,5 +185,10 @@ pub use blocking_sleep::DefaultBlockingSleeper; #[cfg(feature = "std-blocking-sleep")] pub use blocking_sleep::StdSleeper; +#[cfg(feature = "embassy-sleep")] +mod embassy_timer_sleep; +#[cfg(feature = "embassy-sleep")] +pub use embassy_timer_sleep::EmbassySleeper; + #[cfg(docsrs)] pub mod docs;