timeout_trait/
lib.rs

1//! Traits used to wait and timeout in a `no-std` embedded system.
2//!
3//! It requires an implementation of [`TickInstant`]. In return, it provides [`TickTimeout`]
4//! and [`TickDuration`], which can be used for timeout-related operations. It also includes
5//! an implementation of `DelayNs` called [`TickDelay`], suitable for bare-metal systems.
6//!
7//! # Cargo Features
8//!
9//! - `std`: Used for unit test. Disabled by default.
10
11#![cfg_attr(not(feature = "std"), no_std)]
12
13pub mod delay;
14pub mod duration;
15pub mod fake_impls;
16pub mod prelude;
17#[cfg(feature = "std")]
18pub mod std_impls;
19pub mod timeout;
20
21#[cfg(all(feature = "std", test))]
22mod mock;
23
24pub use delay::TickDelay;
25pub use duration::TickDuration;
26pub use embedded_hal::delay::DelayNs;
27pub use fugit::{self, KilohertzU32};
28pub use timeout::TickTimeout;
29
30/// It doesn't require operation interfaces on `TickInstant` itself.
31/// Embedded systems can thus implement only the relative time version,
32/// which means you can not use it as a global timestamp.
33pub trait TickInstant: Clone {
34    fn frequency() -> KilohertzU32;
35    fn now() -> Self;
36    /// Returns the amount of ticks elapsed since this instant.
37    fn elapsed(&mut self) -> TickDuration<Self>;
38
39    /// Move the instant forward, but it cannot be in the future.
40    fn move_forward(&mut self, dur: &TickDuration<Self>);
41
42    #[inline]
43    fn timeout(&mut self, dur: &TickDuration<Self>) -> bool {
44        &self.elapsed() >= dur
45    }
46
47    fn timeout_with(&self, dur: &TickDuration<Self>, mut f: impl FnMut() -> bool) -> bool {
48        let mut t = Self::now();
49        while f() {
50            if t.timeout(dur) {
51                return true;
52            }
53        }
54        false
55    }
56
57    fn time_left(&mut self, dur: &TickDuration<Self>) -> TickDuration<Self> {
58        let elapsed = &self.elapsed();
59        if elapsed >= dur {
60            TickDuration::ZERO
61        } else {
62            dur - elapsed
63        }
64    }
65}