embedded_hal_mock/eh0/
delay.rs

1//! Delay mock implementations.
2//!
3//! ## Usage
4//!
5//! If the actual sleep duration is not important, simply create a
6//! [`NoopDelay`](struct.NoopDelay.html) instance. There will be no actual
7//! delay. This is useful for fast tests, where you don't actually need to wait
8//! for the hardware.
9//!
10//! If you do want the real delay behavior, use
11//! [`StdSleep`](struct.StdSleep.html) which uses
12//! [`std::thread::sleep`](https://doc.rust-lang.org/std/thread/fn.sleep.html)
13//! to implement the delay.
14
15use std::{thread, time::Duration};
16
17use eh0 as embedded_hal;
18use embedded_hal::blocking::delay;
19
20/// A `Delay` implementation that does not actually block.
21pub struct NoopDelay;
22
23impl NoopDelay {
24    /// Create a new `NoopDelay` instance.
25    pub fn new() -> Self {
26        NoopDelay
27    }
28}
29
30impl Default for NoopDelay {
31    fn default() -> Self {
32        Self::new()
33    }
34}
35
36macro_rules! impl_noop_delay_us {
37    ($type:ty) => {
38        impl delay::DelayUs<$type> for NoopDelay {
39            /// A no-op delay implementation.
40            fn delay_us(&mut self, _n: $type) {}
41        }
42    };
43}
44
45impl_noop_delay_us!(u8);
46impl_noop_delay_us!(u16);
47impl_noop_delay_us!(u32);
48impl_noop_delay_us!(u64);
49
50macro_rules! impl_noop_delay_ms {
51    ($type:ty) => {
52        impl delay::DelayMs<$type> for NoopDelay {
53            /// A no-op delay implementation.
54            fn delay_ms(&mut self, _n: $type) {}
55        }
56    };
57}
58
59impl_noop_delay_ms!(u8);
60impl_noop_delay_ms!(u16);
61impl_noop_delay_ms!(u32);
62impl_noop_delay_ms!(u64);
63
64/// A `Delay` implementation that uses `std::thread::sleep`.
65pub struct StdSleep;
66
67impl StdSleep {
68    /// Create a new `StdSleep` instance.
69    pub fn new() -> Self {
70        StdSleep
71    }
72}
73
74impl Default for StdSleep {
75    fn default() -> Self {
76        Self::new()
77    }
78}
79
80macro_rules! impl_stdsleep_delay_us {
81    ($type:ty) => {
82        impl delay::DelayUs<$type> for StdSleep {
83            /// A `Delay` implementation that uses `std::thread::sleep`.
84            fn delay_us(&mut self, n: $type) {
85                thread::sleep(Duration::from_micros(n as u64));
86            }
87        }
88    };
89}
90
91impl_stdsleep_delay_us!(u8);
92impl_stdsleep_delay_us!(u16);
93impl_stdsleep_delay_us!(u32);
94impl_stdsleep_delay_us!(u64);
95
96macro_rules! impl_stdsleep_delay_ms {
97    ($type:ty) => {
98        impl delay::DelayMs<$type> for StdSleep {
99            /// A `Delay` implementation that uses `std::thread::sleep`.
100            fn delay_ms(&mut self, n: $type) {
101                thread::sleep(Duration::from_millis(n as u64));
102            }
103        }
104    };
105}
106
107impl_stdsleep_delay_ms!(u8);
108impl_stdsleep_delay_ms!(u16);
109impl_stdsleep_delay_ms!(u32);
110impl_stdsleep_delay_ms!(u64);