os_trait/
lib.rs

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