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