zephyr/
device.rs

1//! Device wrappers
2//!
3//! This module contains implementations of wrappers for various types of devices in zephyr.  In
4//! general, these wrap a `*const device` from Zephyr, and provide an API that is appropriate.
5//!
6//! Most of these instances come from the device tree.
7
8// Allow for a Zephyr build that has no devices at all.
9#![allow(dead_code)]
10
11use crate::sync::atomic::{AtomicBool, Ordering};
12
13#[cfg(CONFIG_FLASH)]
14pub mod flash;
15#[cfg(CONFIG_GPIO)]
16pub mod gpio;
17
18// Allow dead code, because it isn't required for a given build to have any devices.
19/// Device uniqueness.
20///
21/// As the zephyr devices are statically defined structures, this `Unique` value ensures that the
22/// user is only able to get a single instance of any given device.
23///
24/// Note that some devices in zephyr will require more than one instance of the actual device.  For
25/// example, a [`GpioPin`] will reference a single pin, but the underlying device for the gpio
26/// driver will be shared among then.  Generally, the constructor for the individual device will
27/// call `get_instance_raw()` on the underlying device.
28pub(crate) struct Unique(pub(crate) AtomicBool);
29
30impl Unique {
31    // Note that there are circumstances where these are in zero-initialized memory, so false must
32    // be used here, and the result of `once` inverted.
33    /// Construct a new unique counter.
34    pub(crate) const fn new() -> Unique {
35        Unique(AtomicBool::new(false))
36    }
37
38    /// Indicates if this particular entity can be used.  This function, on a given `Unique` value
39    /// will return true exactly once.
40    pub(crate) fn once(&self) -> bool {
41        // `fetch_add` is likely to be faster than compare_exchage.  This does have the limitation
42        // that `once` is not called more than `usize::MAX` times.
43        !self.0.fetch_or(true, Ordering::AcqRel)
44    }
45}
46
47/// For devices that don't need any associated static data, This NoStatic type will take no space
48/// and generate no code, and has the const constructor needed for the type.
49pub(crate) struct NoStatic;
50
51impl NoStatic {
52    pub(crate) const fn new() -> Self {
53        Self
54    }
55}