timeout_trait/
lib.rs

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