os_trait/
lib.rs

1//! Traits used to adapter different embedded RTOS.
2//! See [`OsInterface`]
3//!
4//! # Cargo Features
5//!
6//! - `alloc`: Enabled by default.
7//! - `std`: Used for unit test. Disabled by default.
8//! - `std-custom-mutex`: Enable it when you want to use `BlockingMutex` instead of STD `Mutex` in STD environment.
9
10#![cfg_attr(not(feature = "std"), no_std)]
11
12pub mod mutex_impls;
13pub mod notifier;
14pub mod notifier_impls;
15pub mod os_impls;
16pub mod prelude;
17
18pub use embedded_hal;
19pub use fugit;
20pub use mutex_impls::{FakeRawMutex, Mutex};
21pub use mutex_traits;
22pub use mutex_traits::{ConstInit, RawMutex};
23pub use notifier_impls::*;
24pub use os_impls::{FakeOs, StdOs};
25pub use timeout_trait::{self, *};
26
27use crate::prelude::*;
28
29#[cfg(feature = "alloc")]
30extern crate alloc;
31
32/// Adapter for different operating systems.
33///
34/// We use the [`mutex-traits`](https://crates.io/crates/mutex-traits) crate to provide mutex functionality.
35/// You need to select an appropriate mutex implementation based on your needs.
36/// And you can implement your own mutex by implementing the `RawMutex` trait from the `mutex-traits` crate.
37///
38/// ```
39/// use os_trait::{prelude::*, FakeOs, StdOs, Duration, Timeout};
40///
41/// fn use_os<OS: OsInterface>() {
42///     let mutex = OS::mutex(2);
43///
44///     let mut guard = mutex.try_lock().unwrap();
45///     assert_eq!(*guard, 2);
46///
47///     OS::yield_thread();
48///
49///     OS::delay().delay_ms(1);
50///
51///     let mut t = Timeout::<OS>::from_millis(1);
52///     if t.timeout() {
53///         // handle timeout
54///     }
55/// }
56///
57/// fn select_os() {
58///     use_os::<FakeOs>();
59///     use_os::<StdOs>();
60/// }
61/// ```
62pub trait OsInterface: Send + Sync + Sized + 'static {
63    type RawMutex: ConstInit + RawMutex;
64    type Notifier: Notifier;
65    type NotifyWaiter: NotifyWaiter<Self>;
66    type Instant: TickInstant;
67    type Delay: DelayNs;
68
69    /// It's used to avoid writing `foo::<OS, _, _, _>(...)`
70    const O: Self;
71
72    fn yield_thread();
73
74    #[inline(always)]
75    fn yield_task() {
76        Self::yield_thread()
77    }
78
79    fn delay() -> Self::Delay;
80    fn notify() -> (Self::Notifier, Self::NotifyWaiter);
81
82    #[inline]
83    fn mutex<T>(d: T) -> Mutex<Self, T> {
84        Mutex::<Self, T>::new(d)
85    }
86}
87
88pub type Timeout<OS> = TickTimeout<<OS as OsInterface>::Instant>;
89pub type Duration<OS> = TickDuration<<OS as OsInterface>::Instant>;