Skip to main content

bnb/guide/
bitfields.rs

1//! `#[bitfield]` — pack typed fields into one backing integer.
2//!
3//! A `#[bitfield]` collapses a struct of `Bits`-typed fields into a single unsigned
4//! integer, generating accessors that shift and mask. It is the tool for a run of
5//! sub-byte fields that together fill one word (a flags/opcode byte, a VLAN tag, an
6//! IPv4 first byte).
7//!
8//! ```
9//! use bnb::{bitfield, u4};
10//!
11//! #[bitfield(u8, bits = msb)]
12//! #[derive(Clone, Copy)]
13//! struct VersionIhl {
14//!     version: u4,   // high nibble
15//!     ihl: u4,       // low nibble
16//! }
17//!
18//! let b = VersionIhl::new().with_version(u4::new(4)).with_ihl(u4::new(5));
19//! assert_eq!(b.raw(), 0x45);          // the classic IPv4 first byte
20//! assert_eq!(b.version().value(), 4);
21//! ```
22//!
23//! # Generated API
24//!
25//! For a field `f: T`, you get `f() -> T`, `with_f(T) -> Self` (consuming, chainable),
26//! and `set_f(&mut self, T)`. Plus `new()` (all-zero), `raw()`/`from_raw()`, and
27//! allocation-free `to_be_bytes`/`to_le_bytes`/`from_be_bytes`/`from_le_bytes`. The
28//! type also implements [`Bits`](crate::Bits) and [`Bitfield`](crate::Bitfield), so
29//! it nests in another bitfield or a `#[bin]` message.
30//!
31//! ```
32//! use bnb::{bitfield, u4};
33//! # #[bitfield(u8, bits = msb)] #[derive(Clone, Copy)] struct VersionIhl { version: u4, ihl: u4 }
34//! let mut b = VersionIhl::new().with_version(u4::new(4)).with_ihl(u4::new(5));
35//! b.set_ihl(u4::new(6));
36//! assert_eq!(b.ihl().value(), 6);
37//! assert_eq!(VersionIhl::from_be_bytes([0x45]).version().value(), 4);
38//! ```
39//!
40//! # Bit order vs. byte order — two independent knobs
41//!
42//! - `bits = msb | lsb` (default `msb`): does the **first** declared field land in the
43//!   high or low bits of the backing integer. `msb` matches the ASCII-art layouts in
44//!   RFCs (first field drawn leftmost = most significant).
45//! - `bytes = be | le` (default `be`): the byte order of the backing integer when
46//!   serialized to bytes.
47//!
48//! They are orthogonal. The same fields, packed `msb` but emitted `le`:
49//!
50//! ```
51//! use bnb::{bitfield, u4};
52//!
53//! #[bitfield(u16, bits = msb, bytes = be)]
54//! #[derive(Clone, Copy)]
55//! struct Be { hi: u4, mid: u8, lo: u4 }
56//!
57//! #[bitfield(u16, bits = msb, bytes = le)]
58//! #[derive(Clone, Copy)]
59//! struct Le { hi: u4, mid: u8, lo: u4 }
60//!
61//! let be = Be::new().with_hi(u4::new(0xA)).with_mid(0xBC).with_lo(u4::new(0xD));
62//! let le = Le::new().with_hi(u4::new(0xA)).with_mid(0xBC).with_lo(u4::new(0xD));
63//! assert_eq!(be.to_be_bytes(), [0xAB, 0xCD]); // same logical value...
64//! assert_eq!(le.to_le_bytes(), [0xCD, 0xAB]); // ...different wire bytes
65//! ```
66//!
67//! # Field widths: inferred, explicit, or ranged
68//!
69//! In order of precedence:
70//!
71//! 1. **Inferred** (no attribute): the field's width is `<T as Bits>::BITS`. Fields
72//!    pack adjacently in declaration order. This is the common case.
73//! 2. **`#[bits(N)]`**: an explicit width, still auto-placed. Useful when a field's
74//!    type is wider than the bits it should occupy.
75//! 3. **`#[bits(A..=B)]`**: an absolute, inclusive bit range — fully manual layout,
76//!    the equivalent of `bitbybit`'s `bits = A..=B`. Use ranges on **every** field, or
77//!    on none; the two styles can't be mixed in one struct.
78//!
79//! With inferred widths the declared total is the sum of the fields (gaps are not
80//! transmitted); with ranges the width is the whole backing integer (gaps are real
81//! reserved bits on the wire).
82//!
83//! ```
84//! use bnb::bitfield;
85//!
86//! // Manual layout: two fields with a deliberate 3-bit gap inside a u32.
87//! #[bitfield(u32, bits = msb)]
88//! #[derive(Clone, Copy)]
89//! struct Manual {
90//!     #[bits(20..=31)] tag: bnb::u12,   // top 12 bits
91//!     #[bits(0..=16)]  body: bnb::u17,  // low 17 bits; bits 17..=19 are reserved
92//! }
93//!
94//! let m = Manual::new().with_tag(bnb::u12::new(0xABC)).with_body(bnb::u17::new(1));
95//! assert_eq!(m.tag().value(), 0xABC);
96//! assert_eq!(m.body().value(), 1);
97//! ```
98//!
99//! A reversed range (`#[bits(31..=20)]`) is a clear compile error, not a silent
100//! overflow, and field widths that exceed the backing integer fail a const assert.
101//!
102//! # Nesting
103//!
104//! Because a `#[bitfield]` is itself a `Bits` value, bitfields nest. A 5-bit field of
105//! a nested type contributes exactly 5 bits to its parent:
106//!
107//! ```
108//! use bnb::{bitfield, BitEnum, u3, u5};
109//!
110//! #[derive(BitEnum, Clone, Copy, Debug, PartialEq, Eq)]
111//! #[bit_enum(u3)]
112//! enum Op { Read, Write, #[catch_all] Other(u3) }
113//!
114//! #[bitfield(u8, bits = msb)]
115//! #[derive(Clone, Copy)]
116//! struct Cmd { op: Op, addr: u5 }      // 3 + 5 = 8 bits exactly
117//!
118//! let c = Cmd::new().with_op(Op::Write).with_addr(u5::new(0x11));
119//! assert_eq!(c.op(), Op::Write);
120//! assert_eq!(c.addr().value(), 0x11);
121//! ```
122//!
123//! See [`enums`](super::enums) and [`flags`](super::flags) for the field types that
124//! nest here, and [`composition`](super::composition) for the full picture.