os_trait/
os_impls.rs

1use crate::{
2    mutex_impls::*,
3    notifier_impls::*,
4    prelude::*,
5    timeout_trait::{delay_impls::*, fake_impls::*},
6};
7cfg_if::cfg_if! {
8    if #[cfg(feature = "std")] {
9        use std::thread;
10        use crate::timeout_trait::std_impls::*;
11    }
12}
13
14// STD --------------------------------------------------------------
15
16/// This implementation is only for unit testing.
17pub struct StdOs;
18#[cfg(feature = "std")]
19impl OsInterface for StdOs {
20    type RawMutex = FakeRawMutex;
21    type NotifyBuilder = StdNotifier;
22    type Timeout = StdTimeoutNs;
23
24    fn yield_thread() {
25        thread::yield_now();
26    }
27
28    fn delay() -> impl DelayNs {
29        StdDelayNs {}
30    }
31}
32
33// Fake -------------------------------------------------------------
34
35pub struct FakeOs;
36impl OsInterface for FakeOs {
37    type RawMutex = FakeRawMutex;
38    type NotifyBuilder = FakeNotifier;
39    type Timeout = FakeTimeoutNs;
40
41    fn yield_thread() {}
42
43    fn delay() -> impl DelayNs {
44        TickDelay::<FakeInstant>::default()
45    }
46}
47
48// Tests ------------------------------------------------------------
49
50#[cfg(feature = "std")]
51#[cfg(test)]
52mod tests {
53    use super::*;
54    use crate::fugit::ExtU32;
55
56    fn os_interface<OS: OsInterface>() {
57        let mutex = OS::mutex(0);
58
59        let mut guard = mutex.try_lock().unwrap();
60        assert_eq!(*guard, 0);
61        *guard = 4;
62        drop(guard);
63
64        mutex
65            .try_with_lock(|data| {
66                assert_eq!(*data, 4);
67                *data = 5;
68            })
69            .unwrap();
70
71        OS::yield_thread();
72        OS::delay().delay_ms(1);
73
74        let (n, r) = OS::notifier_isr();
75        n.notify_from_isr();
76        assert!(r.wait(1.millis()));
77
78        let (n, r) = OS::notifier();
79        n.notify();
80        assert!(r.wait(1.millis()));
81    }
82
83    #[test]
84    fn select_os() {
85        os_interface::<FakeOs>();
86        os_interface::<StdOs>();
87    }
88}