Skip to main content

Bitfield

Trait Bitfield 

Source
pub trait Bitfield: Bits + Sized {
    type Backing: Copy;

    const WIDTH: u32;
    const BYTE_ORDER: ByteOrder;
    const BIT_ORDER: BitOrder;

    // Required methods
    fn to_raw(self) -> Self::Backing;
    fn from_raw(raw: Self::Backing) -> Self;
}
Expand description

The seam every #[bitfield] struct implements — the stable interface the #[bin] codec builds on, independent of how the fields are accessed.

A bitfield is a thin wrapper over a single backing unsigned integer; this trait exposes that backing plus the declared layout metadata. The generated type also provides allocation-free byte conversions: inherent to_bytes/from_bytes (which use the declared BYTE_ORDER) plus the endianness-explicit to_be_bytes/to_le_bytes/from_be_bytes/from_le_bytes.

§Examples

use bnb::{bitfield, u4, Bitfield, BitOrder, ByteOrder};

#[bitfield(u8, bits = msb, bytes = big)]
#[derive(Clone, Copy)]
struct Byte { hi: u4, lo: u4 }

let b = Byte::new().with_hi(u4::new(0xA)).with_lo(u4::new(0xB));
assert_eq!(b.to_raw(), 0xAB);              // the backing integer
assert_eq!(Byte::from_raw(0xCD).hi().value(), 0xC);
assert_eq!(Byte::WIDTH, 8);                // declared layout metadata
assert_eq!(Byte::BYTE_ORDER, ByteOrder::Big);
assert_eq!(Byte::BIT_ORDER, BitOrder::Msb);

Required Associated Constants§

Source

const WIDTH: u32

The declared total bit width (may be less than the backing’s width, the remainder being reserved/padding).

Source

const BYTE_ORDER: ByteOrder

The byte order in which the backing integer is serialized.

Source

const BIT_ORDER: BitOrder

The bit packing order of the declared fields.

Required Associated Types§

Source

type Backing: Copy

The backing primitive integer (u8, u16, u32, u64, or u128).

Required Methods§

Source

fn to_raw(self) -> Self::Backing

The raw backing integer.

Source

fn from_raw(raw: Self::Backing) -> Self

Construct directly from a raw backing integer (no validation — the dual-use escape hatch).

Dyn Compatibility§

This trait is not dyn compatible.

In older versions of Rust, dyn compatibility was called "object safety".

Implementors§