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