hardware_registers/
lib.rs

1//! # Hardware Register Traits
2//!
3//! Generic, embedded-friendly hardware registers support, including
4//! traits and types for understanding I²C registers.
5
6#![cfg_attr(not(feature = "std"), no_std)]
7#![forbid(unsafe_code)]
8#![deny(warnings, clippy::pedantic)]
9#![warn(
10    clippy::expect_used,
11    clippy::missing_errors_doc,
12    clippy::unwrap_used,
13    missing_debug_implementations,
14    missing_docs,
15    rust_2018_idioms,
16    rust_2021_compatibility,
17    unused_qualifications
18)]
19// Enables the `doc_cfg` feature when the `docsrs` configuration attribute is defined.
20#![cfg_attr(docsrs, feature(doc_cfg))]
21
22use crate::sizes::RegisterSizeInformation;
23
24#[cfg(feature = "i2c")]
25#[cfg_attr(docsrs, doc(cfg(feature = "i2c")))]
26pub mod i2c;
27pub mod sizes;
28#[cfg(feature = "spi")]
29#[cfg_attr(docsrs, doc(cfg(feature = "spi")))]
30pub mod spi;
31
32pub mod register_address;
33
34/// A generic hardware register of specified byte size.
35pub trait HardwareRegister<Size>
36where
37    Size: RegisterSizeInformation,
38{
39    /// The size of the register in bytes.
40    const SIZE_BYTES: usize = Size::BYTES;
41
42    /// The size of the register in bits.
43    const SIZE_BITS: usize = Size::BITS;
44}
45
46/// A writable hardware register of specified byte size.
47pub trait WritableHardwareRegister<Size>: HardwareRegister<Size>
48where
49    Size: RegisterSizeInformation,
50{
51}
52
53/// Conversion to bits/bytes.
54pub trait ToBits {
55    /// The target type.
56    type Target;
57
58    /// Converts the value into an underlying bit/byte representation
59    fn to_bits(&self) -> Self::Target;
60}
61
62/// Conversion from bits/bytes.
63pub trait FromBits<B>: Sized {
64    /// Converts the value into an underlying bit/byte representation
65    #[inline]
66    fn from_bits(value: B) -> Self {
67        Self::from_bits_ref(&value)
68    }
69
70    /// Converts the value into an underlying bit/byte representation
71    fn from_bits_ref(value: &B) -> Self;
72}
73
74#[cfg(test)]
75mod tests {
76    use super::*;
77    use crate::sizes::R1;
78
79    struct TestRegister;
80
81    impl HardwareRegister<R1> for TestRegister {}
82
83    #[test]
84    fn constant_size_usable() {
85        // Ensure that the constant can be used to do calculations.
86        let _ = [0_u8; TestRegister::SIZE_BYTES * 2];
87    }
88}