waiter_trait/
lib.rs

1//! Traits used to wait and timeout in a `no-std` embedded system.
2//!
3//! ## Features
4//!
5//!- `std`: Disabled by default.
6//!
7//! # Examples
8//!
9//! ```
10//! use waiter_trait::{Waiter, WaiterTime, StdWaiter};
11//! use std::time::Duration;
12//!
13//! // Initialize limit time and interval time.
14//! let waiter = StdWaiter::new(Duration::from_millis(80), Some(Duration::from_millis(50)));
15//!
16//! fn foo(waiter: impl Waiter) {
17//!     let mut t = waiter.start();
18//!     loop {
19//!         // Wait for something.
20//!
21//!         // Reset if it's necessary.
22//!         t.restart();
23//!
24//!         if t.timeout() {
25//!             break;
26//!         }
27//!     }
28//! }
29//! ```
30//!
31//! ## Implementations
32//!
33//! For developers, you can choose one of the following options.
34//! - Implement [`Waiter`] and [`WaiterTime`] then use them.
35//! - Implement [`TickInstant`] and [`Interval`] then use [`TickWaiter`].
36//!     - If you want to do nothing in `interval()`, just use [`NonInterval`].
37//! - If you can't use a timer, you can consider to use [`Counter`]
38//!
39//! It also provides a implementation of `DelayNs` named [`TickDelay`]
40
41#![cfg_attr(not(feature = "std"), no_std)]
42
43mod counter;
44pub use counter::*;
45mod non_interval;
46pub use non_interval::*;
47mod tick_waiter;
48pub use tick_waiter::*;
49mod tick_delay;
50pub use tick_delay::*;
51#[cfg(feature = "std")]
52mod std_impls;
53#[cfg(feature = "std")]
54pub use std_impls::*;
55
56pub trait Waiter {
57    /// Start waiting.
58    fn start(&self) -> impl WaiterTime;
59}
60
61pub trait WaiterTime {
62    /// Check if the time limit expires. This function may sleeps for a while,
63    /// depends on the implementation.
64    fn timeout(&mut self) -> bool;
65    /// Reset the timeout condition.
66    fn restart(&mut self);
67}
68
69pub trait TickInstant: Copy {
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}
78
79/// Can be implement for `yield`, `sleep` or do nothing.
80pub trait Interval: Clone {
81    fn interval(&self);
82}