#[bitfield]Expand description
Packs the annotated struct’s fields into a single backing integer.
#[bitfield(u16, bits = msb, bytes = big)]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
struct State {
opcode: u5, // first field -> high bits (msb)
flags: Flags, // a nested bitfield
rcode: RCode, // a BitEnum; last field -> low bits
}§Attribute arguments
- backing (first, required): the storage primitive —
u8,u16,u32,u64, oru128. Must be at least as wide as the fields. bits = msb | lsb(defaultmsb): whether the first declared field lands in the high or low bits.bytes = big | little(defaultbig): byte order of the backing integer when serialized.
§Field widths
A field’s width is, in order of precedence: an explicit #[bits(N)]; an
explicit #[bits(A..=B)] range (which also fixes its absolute offset); or,
by default, <FieldType as bnb::Bits>::BITS. Use widths/inference for
automatic layout, or ranges on every field for fully manual layout — the
two styles cannot be mixed in one struct.
§Generated API
new() (all-zero; derive Default yourself if you want it),
with_<field>/set_<field>, <field>()
getters, to_raw()/from_raw(), to_be_bytes()/to_le_bytes()/
from_be_bytes()/from_le_bytes(), and bnb::{Bits, Bitfield} impls.
Every accessor is a const fn (#[view] accessors too, when their raw
type is annotated — the view’s const argument asserts it, dynamic opts
out; see bnb::guide::bitfields. A custom field type is implemented with
bnb::impl_bits! — see bnb::Bits).
§Layout
The emitted struct is #[repr(transparent)] over its backing integer:
its size, alignment, and ABI are exactly the backing type’s. (transparent,
not repr(C), because the struct wraps a single native integer — that is
the honest guarantee; before 0.3.2 the layout was formally unspecified.)
Writing your own #[repr(...)] on the struct suppresses the generated one
— e.g. repr(C), or repr(align(N)), neither of which can combine with
transparent.
See the bnb::guide::bitfields page for runnable examples (bit/byte order,
inferred vs. ranged widths, nesting).