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, WaiterStatus, 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`], [`TimedWaiter`], and [`WaiterStatus`] then use them.
35//! - Implement [`TickInstant`] and [`Interval`] then use [`TickWaiter`] or [`TimedTickWaiter`].
36//! - If you want to do nothing in the `interval()`, just give it [`NonInterval`],
37//! and in this way you can use `DelayNs` separately.
38//! - Using [`Counter`], if you don't have any tick source.
39//!
40//! It also provides a implementation of `DelayNs` named [`TickDelay`]
41
42#![cfg_attr(not(feature = "std"), no_std)]
43
44mod counter;
45pub use counter::*;
46mod non_interval;
47pub use non_interval::*;
48mod tick_waiter;
49pub use tick_waiter::*;
50mod tick_delay;
51pub use tick_delay::*;
52mod timed_tick_waiter;
53pub use timed_tick_waiter::*;
54
55#[cfg(feature = "std")]
56mod std_impls;
57#[cfg(feature = "std")]
58pub use std_impls::*;
59
60pub use embedded_hal::delay::DelayNs;
61pub use fugit::{self, MicrosDurationU32};
62
63pub mod prelude;
64
65pub trait Waiter {
66 /// Start waiting.
67 fn start(&self) -> impl WaiterStatus;
68}
69
70pub trait TimedWaiter {
71 /// Set timeout and start waiting.
72 fn start(&self, timeout: MicrosDurationU32) -> impl WaiterStatus;
73}
74
75pub trait WaiterStatus {
76 /// Check if the time limit expires. This function may sleeps for a while,
77 /// depends on the implementation.
78 fn timeout(&mut self) -> bool;
79 /// Reset the timeout condition.
80 fn restart(&mut self);
81}
82
83pub trait TickInstant: Copy {
84 fn now() -> Self;
85 /// Returns the amount of ticks elapsed from another instant to this one.
86 fn tick_since(self, earlier: Self) -> u32;
87 /// Returns the amount of ticks elapsed since this instant.
88 fn tick_elapsed(self) -> u32 {
89 Self::now().tick_since(self)
90 }
91}
92
93/// Can be implement for `yield`, `sleep` or do nothing.
94pub trait Interval: Clone {
95 fn interval(&self);
96}