Skip to main content

rtic_time/
lib.rs

1//! Time-related traits & structs.
2//!
3//! This crate contains basic definitions and utilities that can be used
4//! to keep track of time.
5
6#![no_std]
7#![deny(missing_docs)]
8#![allow(async_fn_in_trait)]
9
10pub mod half_period_counter;
11mod linked_list;
12pub mod monotonic;
13pub mod timer_queue;
14
15/// This indicates that there was a timeout.
16pub struct TimeoutError;
17
18/// Re-export for macros
19pub use embedded_hal;
20/// Re-export for macros
21pub use embedded_hal_async;
22/// Re-export for macros
23pub use fugit;
24
25/// # A clock / counter definition, usable for scheduling.
26///
27/// ## Correctness
28///
29/// The trait enforces that proper time-math is implemented between `Instant` and `Duration`. This
30/// is a requirement on the time library that the user chooses to use.
31///
32/// The instants carry no ordering requirement, which admits timelines that wrap. On a wrapping
33/// timebase, scheduling is only meaningful within half the counter range of `now`.
34pub trait Timebase {
35    /// The type for instant, defining an instant in time.
36    ///
37    /// **Note:** In all APIs in RTIC that use instants from this monotonic, this type will be used.
38    type Instant: Copy
39        + core::ops::Add<Self::Duration, Output = Self::Instant>
40        + core::ops::Sub<Self::Duration, Output = Self::Instant>
41        + core::ops::Sub<Self::Instant, Output = Self::Duration>;
42
43    /// The type for duration, defining a duration of time.
44    ///
45    /// **Note:** In all APIs in RTIC that use duration from this monotonic, this type will be used.
46    type Duration: Copy;
47
48    /// Get the current time.
49    fn now() -> Self::Instant;
50
51    /// Delay for some duration of time.
52    async fn delay(duration: Self::Duration);
53
54    /// Delay to some specific time instant.
55    async fn delay_until(instant: Self::Instant);
56
57    /// Timeout at a specific time.
58    async fn timeout_at<F: core::future::Future>(
59        instant: Self::Instant,
60        future: F,
61    ) -> Result<F::Output, TimeoutError>;
62
63    /// Timeout after a specific duration.
64    async fn timeout_after<F: core::future::Future>(
65        duration: Self::Duration,
66        future: F,
67    ) -> Result<F::Output, TimeoutError>;
68}
69
70/// # A monotonic clock / counter definition: a [`Timebase`] whose instants form a total order.
71///
72/// Implemented automatically for every [`Timebase`] whose `Instant` is [`Ord`].
73pub trait Monotonic: Timebase<Instant: Ord> {}
74
75impl<T: Timebase<Instant: Ord>> Monotonic for T {}