embedded_hal_bus/
util.rs

1//! Utilities shared by all bus types.
2
3#[allow(unused_imports)]
4use core::cell::UnsafeCell;
5
6#[cfg(not(feature = "portable-atomic"))]
7use core::sync::atomic::AtomicBool;
8#[cfg(feature = "portable-atomic")]
9use portable_atomic::AtomicBool;
10
11#[cfg(any(feature = "portable-atomic", target_has_atomic = "8"))]
12/// Cell type used by [`spi::AtomicDevice`](crate::spi::AtomicDevice) and [`i2c::AtomicDevice`](crate::i2c::AtomicDevice).
13///
14/// To use `AtomicDevice`, you must wrap the bus with this struct, and then
15/// construct multiple `AtomicDevice` instances with references to it.
16pub struct AtomicCell<BUS> {
17    pub(crate) bus: UnsafeCell<BUS>,
18    pub(crate) busy: AtomicBool,
19}
20#[cfg(any(feature = "portable-atomic", target_has_atomic = "8"))]
21unsafe impl<BUS: Send> Send for AtomicCell<BUS> {}
22#[cfg(any(feature = "portable-atomic", target_has_atomic = "8"))]
23unsafe impl<BUS: Send> Sync for AtomicCell<BUS> {}
24
25#[cfg(any(feature = "portable-atomic", target_has_atomic = "8"))]
26impl<BUS> AtomicCell<BUS> {
27    /// Create a new `AtomicCell`
28    pub fn new(bus: BUS) -> Self {
29        Self {
30            bus: UnsafeCell::new(bus),
31            busy: AtomicBool::from(false),
32        }
33    }
34}