zephyr/
device.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
//! Device wrappers
//!
//! This module contains implementations of wrappers for various types of devices in zephyr.  In
//! general, these wrap a `*const device` from Zephyr, and provide an API that is appropriate.
//!
//! Most of these instances come from the device tree.

// Allow for a Zephyr build that has no devices at all.
#![allow(dead_code)]

use crate::sync::atomic::{AtomicBool, Ordering};

pub mod flash;
pub mod gpio;

// Allow dead code, because it isn't required for a given build to have any devices.
/// Device uniqueness.
///
/// As the zephyr devices are statically defined structures, this `Unique` value ensures that the
/// user is only able to get a single instance of any given device.
///
/// Note that some devices in zephyr will require more than one instance of the actual device.  For
/// example, a [`GpioPin`] will reference a single pin, but the underlying device for the gpio
/// driver will be shared among then.  Generally, the constructor for the individual device will
/// call `get_instance_raw()` on the underlying device.
pub(crate) struct Unique(pub(crate) AtomicBool);

impl Unique {
    // Note that there are circumstances where these are in zero-initialized memory, so false must
    // be used here, and the result of `once` inverted.
    /// Construct a new unique counter.
    pub(crate) const fn new() -> Unique {
        Unique(AtomicBool::new(false))
    }

    /// Indicates if this particular entity can be used.  This function, on a given `Unique` value
    /// will return true exactly once.
    pub(crate) fn once(&self) -> bool {
        // `fetch_add` is likely to be faster than compare_exchage.  This does have the limitation
        // that `once` is not called more than `usize::MAX` times.
        !self.0.fetch_or(true, Ordering::AcqRel)
    }
}

/// For devices that don't need any associated static data, This NoStatic type will take no space
/// and generate no code, and has the const constructor needed for the type.
pub(crate) struct NoStatic;

impl NoStatic {
    pub(crate) const fn new() -> Self {
        Self
    }
}