modular_bitfield/
lib.rs

1#![doc = include_str!("../docs/index.md")]
2#![no_std]
3#![forbid(unsafe_code)]
4#![warn(clippy::pedantic, missing_docs, rust_2018_idioms)]
5
6pub mod error;
7#[doc(hidden)]
8pub mod private;
9
10use self::error::{InvalidBitPattern, OutOfBounds};
11
12#[doc = include_str!("../docs/bitfield.md")]
13pub use modular_bitfield_impl::bitfield;
14
15#[doc = include_str!("../docs/bitfield_specifier.md")]
16pub use modular_bitfield_impl::Specifier;
17
18#[doc(hidden)]
19pub use modular_bitfield_impl::BitfieldSpecifier;
20
21/// The prelude: `use modular_bitfield::prelude::*;`
22pub mod prelude {
23    #[doc(hidden)]
24    pub use super::BitfieldSpecifier;
25    pub use super::{bitfield, specifiers::*, Specifier};
26}
27
28/// Trait implemented by all bitfield specifiers.
29///
30/// Should generally not be implemented directly by users
31/// but through the macros provided by the crate.
32///
33/// # Note
34///
35/// These can be all unsigned fixed-size primitives,
36/// represented by `B1, B2, ... B64` and enums that
37/// derive from `Specifier`.
38pub trait Specifier {
39    /// The amount of bits used by the specifier.
40    const BITS: usize;
41
42    /// The base type of the specifier.
43    ///
44    /// # Note
45    ///
46    /// This is the type that is used internally for computations.
47    type Bytes;
48
49    /// The interface type of the specifier.
50    ///
51    /// # Note
52    ///
53    /// This is the type that is used for the getters and setters.
54    type InOut;
55
56    /// Converts the in-out type into bytes.
57    ///
58    /// # Errors
59    ///
60    /// If the in-out type is out of bounds. This can for example happen if your
61    /// in-out type is `u8` (for `B7`) but you specified a value that is bigger
62    /// or equal to 128 which exceeds the 7 bits.
63    fn into_bytes(input: Self::InOut) -> Result<Self::Bytes, OutOfBounds>;
64
65    /// Converts the given bytes into the in-out type.
66    ///
67    /// # Errors
68    ///
69    /// If the given byte pattern is invalid for the in-out type.
70    /// This can happen for example for enums that have a number of variants which
71    /// is not equal to the power of two and therefore yields some invalid bit
72    /// patterns.
73    fn from_bytes(bytes: Self::Bytes) -> Result<Self::InOut, InvalidBitPattern<Self::Bytes>>;
74}
75
76/// The default set of predefined specifiers.
77pub mod specifiers {
78    ::modular_bitfield_impl::define_specifiers!();
79}