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};
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 = OS::timeout().start_ms(1);
52///     if t.timeout() {}
53/// }
54///
55/// fn select_os() {
56///     use_os::<FakeOs>();
57///     use_os::<StdOs>();
58/// }
59/// ```
60pub trait OsInterface: Send + Sync + 'static {
61    type RawMutex: ConstInit + RawMutex;
62    type Notifier: Notifier;
63    type NotifyWaiter: NotifyWaiter;
64    type Timeout: TimeoutNs<TimeoutState = Self::TimeoutState>;
65    type TimeoutState: TimeoutState;
66    type Delay: DelayNs;
67
68    /// It's used to avoid writing `foo::<OS, _, _, _>(...)`
69    const O: Self;
70
71    fn yield_thread();
72
73    #[inline(always)]
74    fn yield_task() {
75        Self::yield_thread()
76    }
77
78    fn timeout() -> Self::Timeout;
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}