pub trait Bits: Copy {
const BITS: u32;
// Required methods
fn into_bits(self) -> u128;
fn from_bits(raw: u128) -> Self;
}Expand description
A value that occupies a fixed number of bits within a bitfield.
The contract: into_bits yields the value in the low
BITS bits of a u128 (higher bits zero), and
from_bits reconstructs from the low BITS bits of its
argument (higher bits ignored). Implementations must round-trip:
T::from_bits(x.into_bits()) == x for every representable x.
bool, the primitive unsigned integers, and the UInt types
implement it out of the box; #[bitfield] and #[derive(BitEnum)] generate
impls so those types nest as fields too.
§Const dispatch (#[bitfield] field types)
The accessors #[bitfield] generates are const fn. A const fn cannot call
trait methods on stable Rust, so the generated code does not go through this
trait: bool and the primitive unsigned integers are converted inline, and
every other field type is called through a pair of inherent const fns with
the same contract as into_bits/from_bits. UInt and every
#[bitfield]/#[derive(BitEnum)]/#[bitflags] type provides the pair
automatically (their Bits impls delegate to it, so the two can never
disagree). Implement a hand-written field type with
impl_bits!, which emits the trait impl and the
inherent pair from one definition — never write the pair by hand. The trait
alone still suffices everywhere else (the #[bin] codec and the bitstream
derives). Field types must be named directly — a type alias of a primitive
is not recognized by the inline conversion.
use bnb::Bits;
assert_eq!(<u8 as Bits>::BITS, 8);
assert_eq!(0xABu8.into_bits(), 0xAB);
assert_eq!(u8::from_bits(0x1FF), 0xFF); // from_bits truncates to the width
assert!(!bool::from_bits(0b10)); // only the low bit is readRequired Associated Constants§
Required Methods§
Dyn Compatibility§
This trait is not dyn compatible.
In older versions of Rust, dyn compatibility was called "object safety".