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::{AtomicNotifier, FakeNotifier};
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 {
54    type RawMutex: ConstInit + RawMutex;
55    type NotifyBuilder: NotifyBuilder;
56    type Timeout: TimeoutNs;
57
58    fn yield_thread();
59    fn delay() -> impl DelayNs;
60
61    #[inline]
62    fn mutex<T>(d: T) -> Mutex<Self, T> {
63        Mutex::<Self, T>::new(d)
64    }
65
66    #[inline]
67    fn notifier() -> (impl Notifier, impl NotifyWaiter) {
68        Self::NotifyBuilder::build()
69    }
70}