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    fn start_ns(timeout: u32) -> impl TimeoutState;
26    fn start_us(timeout: u32) -> impl TimeoutState;
27    fn start_ms(timeout: u32) -> impl TimeoutState;
28
29    fn ns_with(timeout: u32, mut f: impl FnMut() -> bool) -> bool {
30        let mut t = Self::start_ns(timeout);
31        while f() {
32            if t.timeout() {
33                return true;
34            }
35        }
36        false
37    }
38
39    fn us_with(timeout: u32, mut f: impl FnMut() -> bool) -> bool {
40        let mut t = Self::start_us(timeout);
41        while f() {
42            if t.timeout() {
43                return true;
44            }
45        }
46        false
47    }
48
49    fn ms_with(timeout: u32, mut f: impl FnMut() -> bool) -> bool {
50        let mut t = Self::start_ms(timeout);
51        while f() {
52            if t.timeout() {
53                return true;
54            }
55        }
56        false
57    }
58}
59
60pub trait TimeoutState {
61    /// Check if the time limit expires.
62    fn timeout(&mut self) -> bool;
63    /// Reset the timeout condition.
64    fn restart(&mut self);
65}
66
67pub trait TickInstant: Copy {
68    fn frequency() -> KilohertzU32;
69    fn now() -> Self;
70    /// Returns the amount of ticks elapsed from another instant to this one.
71    fn tick_since(self, earlier: Self) -> u32;
72    /// Returns the amount of ticks elapsed since this instant.
73    fn tick_elapsed(self) -> u32 {
74        Self::now().tick_since(self)
75    }
76}