timeout_trait/
lib.rs

1//! Traits used to wait and timeout in a `no-std` embedded system.
2//!
3//!
4//! # Cargo Features
5//!
6//! - `std`: Disabled by default.
7
8pub mod delay_impls;
9pub mod fake_impls;
10pub mod prelude;
11#[cfg(feature = "std")]
12pub mod std_impls;
13pub mod tick_impl;
14pub mod utils;
15
16pub use delay_impls::TickDelay;
17pub use embedded_hal;
18pub use fake_impls::*;
19pub use fugit::{self, KilohertzU32, MicrosDurationU32};
20pub use tick_impl::{TickTimeoutNs, TickTimeoutState};
21
22pub trait TimeoutNs {
23    fn start_ns(timeout: u32) -> impl TimeoutState;
24    fn start_us(timeout: u32) -> impl TimeoutState;
25    fn start_ms(timeout: u32) -> impl TimeoutState;
26
27    fn ns_with(timeout: u32, mut f: impl FnMut() -> bool) -> bool {
28        let mut t = Self::start_ns(timeout);
29        while f() {
30            if t.timeout() {
31                return true;
32            }
33        }
34        false
35    }
36
37    fn us_with(timeout: u32, mut f: impl FnMut() -> bool) -> bool {
38        let mut t = Self::start_us(timeout);
39        while f() {
40            if t.timeout() {
41                return true;
42            }
43        }
44        false
45    }
46
47    fn ms_with(timeout: u32, mut f: impl FnMut() -> bool) -> bool {
48        let mut t = Self::start_ms(timeout);
49        while f() {
50            if t.timeout() {
51                return true;
52            }
53        }
54        false
55    }
56}
57
58pub trait TimeoutState {
59    /// Check if the time limit expires.
60    fn timeout(&mut self) -> bool;
61    /// Reset the timeout condition.
62    fn restart(&mut self);
63}
64
65pub trait TickInstant: Copy {
66    fn frequency() -> KilohertzU32;
67    fn now() -> Self;
68    /// Returns the amount of ticks elapsed from another instant to this one.
69    fn tick_since(self, earlier: Self) -> u32;
70    /// Returns the amount of ticks elapsed since this instant.
71    fn tick_elapsed(self) -> u32 {
72        Self::now().tick_since(self)
73    }
74}