bnb/guide/bin_codec.rs
1//! `#[bin]` — the unified whole-message codec.
2//!
3//! `#[bin]` folds three things over one struct: the read codec, the write codec, and a
4//! required-by-default builder. Fields are read and written at arbitrary **bit**
5//! offsets, so the same attribute handles byte-aligned headers and sub-byte frames,
6//! and any [`Bits`](crate::Bits) type — including a `#[bitfield]`, `#[derive(BitEnum)]`,
7//! or `#[bitflags]` — drops in as one field with no glue.
8//!
9//! # A DNS header, end to end
10//!
11//! The 12-byte DNS message header (RFC 1035 §4.1.1) is a good tour: a 16-bit flags
12//! word (itself a bitfield of enums and bools) between five `u16` counts/ids.
13//!
14//! ```
15//! use bnb::{bin, bitfield, BitEnum, u3, u4};
16//!
17//! #[derive(BitEnum, Clone, Copy, Debug, PartialEq, Eq)]
18//! #[bit_enum(u4)]
19//! enum OpCode { Query, IQuery, Status, #[catch_all] Other(u4) }
20//!
21//! #[derive(BitEnum, Clone, Copy, Debug, PartialEq, Eq)]
22//! #[bit_enum(u4)]
23//! enum RCode { NoError, FormErr, ServFail, NxDomain, #[catch_all] Other(u4) }
24//!
25//! // The 16-bit flags word, MSB-first (RFC diagram order), big-endian.
26//! #[bitfield(u16, bits = msb, bytes = be)]
27//! #[derive(Clone, Copy, Debug, PartialEq, Eq)]
28//! struct Flags {
29//! qr: bool, opcode: OpCode, aa: bool, tc: bool,
30//! rd: bool, ra: bool, z: u3, rcode: RCode, // 1+4+1+1+1+1+3+4 = 16
31//! }
32//!
33//! #[bin(big)]
34//! #[derive(Debug, Clone, PartialEq)]
35//! struct Header {
36//! id: u16,
37//! flags: Flags, // a 16-bit bitfield, nested as one field
38//! qdcount: u16,
39//! ancount: u16,
40//! nscount: u16,
41//! arcount: u16,
42//! }
43//!
44//! // Build with the required-by-default builder.
45//! let flags = Flags::new().with_qr(true).with_rd(true).with_ra(true);
46//! let h = Header::builder()
47//! .id(0x1234).flags(flags)
48//! .qdcount(1).ancount(1).nscount(0).arcount(0)
49//! .build().unwrap();
50//!
51//! // Encode -> 12 bytes; decode is the exact inverse.
52//! let bytes = h.to_bytes().unwrap();
53//! assert_eq!(bytes.len(), 12);
54//! assert_eq!(&bytes[..4], &[0x12, 0x34, 0x81, 0x80]); // id, then flags 0x8180
55//! assert_eq!(Header::decode_exact(&bytes).unwrap(), h);
56//! ```
57//!
58//! # The generated API
59//!
60//! Every `#[bin]` type gets a consistent surface:
61//!
62//! | Direction | Method | Use |
63//! |---|---|---|
64//! | decode | `decode(&mut S)` | one message from a [`Source`](crate::Source) cursor (`BitReader`/socket/file/[`BitBuf`](crate::BitBuf)), advancing it |
65//! | decode | `decode_exact(&[u8])` | one message that consumes every whole byte |
66//! | decode | `decode_all(&[u8]) -> Vec<_>` | every message in the buffer (bit-aware, layout baked in) |
67//! | decode | `decode_iter(&[u8])` | a lazy iterator over the buffer's messages |
68//! | decode | `peek(&[u8])` | one message, tail-tolerant, no buffer mutation |
69//! | encode | `to_bytes() -> Vec<u8>` | encode to a fresh buffer (**verbatim**) |
70//! | encode | `to_canonical_bytes()` | encode the spec-normalized form (**canonical**) † |
71//! | encode | `encode(&mut W)` | encode to any [`std::io::Write`], following the value's `encode_mode` |
72//! | encode | `bit_encode(&mut K)` | write into an explicit [`Sink`](crate::Sink) — a [`BitEncode`](crate::BitEncode) trait method (`canonical_bit_encode` for the canonical form) |
73//! | build | `builder()` | the required-by-default builder |
74//! | build | `new(fields…)` | positional constructor — every stored field, in declaration order |
75//!
76//! `decode_exact`/`decode_all`/`peek`/`to_bytes` are the everyday slice/`Vec` path;
77//! `decode`/`encode(&mut W)`/`bit_encode` open the door to the
78//! [I/O ladder](super::io). († `to_canonical_bytes`, the canonical helpers, and the settable
79//! `encode_mode` exist only when the message has a `reserved` or `calc` field — see
80//! [Two encode forms](#two-encode-forms-verbatim-vs-canonical).)
81//!
82//! ## Decoding a buffer of messages
83//!
84//! `decode_all` / `decode_iter` walk a `&[u8]` of back-to-back messages — bit-aware (a message
85//! needn't end on a byte boundary) and decoding in the message's own byte/bit order:
86//!
87//! ```
88//! use bnb::bin;
89//! #[bin(big)]
90//! #[derive(Debug, PartialEq, Eq)]
91//! struct Ping { seq: u16 }
92//!
93//! let wire = [0x00, 0x01, 0x00, 0x02, 0x00, 0x03]; // three Pings, back to back
94//! assert_eq!(Ping::decode_all(&wire).unwrap(),
95//! vec![Ping { seq: 1 }, Ping { seq: 2 }, Ping { seq: 3 }]);
96//! // decode_iter is the lazy form (yields Result per message):
97//! assert_eq!(Ping::decode_iter(&wire).filter_map(Result::ok).count(), 3);
98//! ```
99//!
100//! For a *cursor* — a stream, socket, or [`BitBuf`](crate::BitBuf) — reach for `decode(&mut S)`
101//! instead (see the [I/O ladder](super::io)).
102//!
103//! # Struct-level options
104//!
105//! Inside `#[bin(...)]`:
106//!
107//! - `big` / `little` — byte order (default `big`).
108//! - `bit_order = msb | lsb` — bit order (default `msb`).
109//! - `magic = <expr>` — a leading constant verified on read, emitted on write.
110//! - `read_only` / `write_only` — generate only one direction.
111//! - `no_builder` — skip the builder.
112//! - `forward_only` — bound decoding to a forward `Source` (a seek directive is then a
113//! compile error).
114//! - `ctx(name: Ty, …)` — declare context the message needs from its parent.
115//! - `validate = <path>` — a soundness check run by `build()`.
116//!
117//! ## Each option, by example
118//!
119//! Byte and bit order:
120//!
121//! ```
122//! use bnb::{bin, u4};
123//!
124//! #[bin(little)] // little-endian byte order
125//! #[derive(Debug, PartialEq)]
126//! struct Le { v: u32 }
127//! assert_eq!(Le { v: 0x1234_5678 }.to_bytes().unwrap(), [0x78, 0x56, 0x34, 0x12]);
128//!
129//! #[bin(big, bit_order = lsb)] // the first field lands in the LOW bits of the byte
130//! #[derive(Debug, PartialEq)]
131//! struct Lsb { a: u4, b: u4 }
132//! assert_eq!(Lsb { a: u4::new(0xA), b: u4::new(0xB) }.to_bytes().unwrap(), [0xBA]);
133//! ```
134//!
135//! Directional codecs and the builder:
136//!
137//! ```
138//! use bnb::bin;
139//!
140//! #[bin(big, read_only)] // only decodes — no `to_bytes`/`encode`
141//! #[derive(Debug, PartialEq)]
142//! struct Ro { v: u16 }
143//! assert_eq!(Ro::decode_exact(&[0x12, 0x34]).unwrap(), Ro { v: 0x1234 });
144//!
145//! #[bin(big, write_only)] // only encodes — no `decode`/`peek`
146//! struct Wo { v: u16 }
147//! assert_eq!(Wo { v: 0x1234 }.to_bytes().unwrap(), [0x12, 0x34]);
148//!
149//! #[bin(big, no_builder)] // no `Nb::builder()` — construct directly
150//! #[derive(Debug, PartialEq)]
151//! struct Nb { v: u16 }
152//! assert_eq!(Nb { v: 5 }.to_bytes().unwrap(), [0x00, 0x05]);
153//! ```
154//!
155//! `forward_only` — decode from a non-seekable stream, with a compile-time no-seek
156//! guarantee (a `#[br(restore_position)]` field would then be a compile error):
157//!
158//! ```
159//! use bnb::{bin, StreamBitReader};
160//!
161//! #[bin(big, forward_only)]
162//! #[derive(Debug, PartialEq)]
163//! struct Hdr { magic: u16, len: u16 }
164//!
165//! let data: &[u8] = &[0xCA, 0xFE, 0x00, 0x10]; // `&[u8]` is `Read` but not `Seek`
166//! let mut s = StreamBitReader::new(data);
167//! assert_eq!(Hdr::decode(&mut s).unwrap(), Hdr { magic: 0xCAFE, len: 16 });
168//! ```
169//!
170//! `ctx(...)` — context a message needs from its parent **to decode**. The parent passes it
171//! with `#[br(ctx { … })]`; standalone, `decode_with`/`decode_with_exact` take a `…Ctx`
172//! (built positionally with `…Ctx::new`). `ctx` is **decode-only**: encode stays a plain
173//! `to_bytes()` unless the *write* side actually reads a ctx param (a keyed `bw(map)`,
174//! `calc`, or `write_with`), in which case the type gets `to_bytes_with`/`encode_with`:
175//!
176//! ```
177//! use bnb::bin;
178//!
179//! #[bin(big, ctx(len: u16))]
180//! #[derive(Debug, PartialEq)]
181//! struct Body {
182//! #[br(count = len)]
183//! data: Vec<u8>,
184//! }
185//!
186//! #[bin(big)]
187//! #[derive(Debug, PartialEq)]
188//! struct Packet {
189//! len: u16,
190//! #[br(ctx { len })] // pass `len` to `Body`
191//! body: Body,
192//! }
193//!
194//! let p = Packet { len: 3, body: Body { data: vec![1, 2, 3] } };
195//! assert_eq!(p.to_bytes().unwrap(), [0x00, 0x03, 1, 2, 3]);
196//! assert_eq!(Packet::decode_exact(&[0x00, 0x03, 1, 2, 3]).unwrap(), p);
197//!
198//! // Standalone: decode needs the context (build it with `BodyCtx::new`); encode is
199//! // plain — `ctx` is decode-only, and `Body`'s write side doesn't read `len`.
200//! let b = Body::decode_with_exact(&[0xAA, 0xBB], BodyCtx::new(2)).unwrap();
201//! assert_eq!(b.data, vec![0xAA, 0xBB]);
202//! assert_eq!(b.to_bytes().unwrap(), vec![0xAA, 0xBB]);
203//! ```
204//!
205//! (`magic` and `validate` are shown below.)
206//!
207//! # Dual-use: `validate` gates the builder, not the parser
208//!
209//! `validate = path` runs a `fn(&Self) -> Result<(), impl Display>` in `build()` only.
210//! The **parser stays permissive** — it never rejects representable input — so a
211//! deliberately malformed message is still decodable (for fuzzing / interop), even
212//! though it can't be *built*. It's also exposed as re-runnable methods: `build()` checks
213//! once, but a value can be mutated before you send it, so **`validate()` / `is_valid()`
214//! re-check the *current* value on demand** (computed, never a stale flag). By convention
215//! `validate` expresses **semantic** soundness — not `calc`/`reserved` fields, which are
216//! representational (normalized by `to_canonical_bytes`), so it's a property of the message's
217//! meaning that holds for the canonical form too.
218//!
219//! ```
220//! use bnb::bin;
221//!
222//! #[bin(big, validate = check)]
223//! #[derive(Debug, PartialEq)]
224//! struct Msg { kind: u8, len: u8 }
225//!
226//! fn check(m: &Msg) -> Result<(), String> {
227//! if m.kind == 0 { return Err("kind 0 is reserved".into()); }
228//! Ok(())
229//! }
230//!
231//! assert!(Msg::builder().kind(0).len(4).build().is_err()); // builder: rejected
232//! assert!(Msg::decode_exact(&[0x00, 0x04]).is_ok()); // parser: permissive
233//!
234//! let mut m = Msg::builder().kind(1).len(4).build().unwrap();
235//! assert!(m.is_valid()); // sound as built
236//! m.kind = 0; // mutated before sending…
237//! assert!(!m.is_valid()); // …re-check catches it
238//! ```
239//!
240//! # Derived, never-drifting fields
241//!
242//! A length or count you don't want to store can be read into a temp local and
243//! recomputed on write, so it can never disagree with the data. Here `len` drives a
244//! `count`-bound `Vec` on read and is recomputed from `payload.len()` on write:
245//!
246//! ```
247//! use bnb::bin;
248//!
249//! #[bin(big, magic = 0xCAFEu16)]
250//! #[derive(Debug, PartialEq)]
251//! struct Frame {
252//! #[br(temp)]
253//! #[bw(calc = self.payload.len() as u8)]
254//! len: u8,
255//! #[br(count = len)]
256//! payload: Vec<u8>,
257//! }
258//!
259//! let f = Frame::builder().payload(vec![0xDE, 0xAD, 0xBE, 0xEF]).build().unwrap();
260//! assert_eq!(f.to_bytes().unwrap(), [0xCA, 0xFE, 0x04, 0xDE, 0xAD, 0xBE, 0xEF]);
261//! assert_eq!(Frame::decode_exact(&[0xCA, 0xFE, 0x02, 0x01, 0x02]).unwrap().payload, vec![1, 2]);
262//! ```
263//!
264//! When the count sits *immediately before* its `Vec` (as here), the whole triad
265//! collapses to one directive on the `Vec` — `#[brw(count_prefix = u8)] payload:
266//! Vec<u8>` — same wire bytes, plus a checked (never-truncating) length on encode.
267//! See [`directives`](super::directives) § `count_prefix`.
268//!
269//! ## `temp` + `calc` vs a stored `calc`
270//!
271//! Whether a `calc` field is also `temp` is the choice between *never keep it* and *keep it
272//! but be able to recompute it*:
273//!
274//! - **`temp` + `calc`** (above) — the field is **not stored**: it's read into a local, written
275//! from the expression, and absent from the struct. Use it for purely-derived prefixes you
276//! never need to read back (a `len`/`count`). It always recomputes, so it creates **no
277//! verbatim/canonical gap** — there's nothing to drift.
278//! - **`calc` *without* `temp`** — the field **is stored** (you can read the decoded value, e.g.
279//! an as-received checksum), and `to_bytes` writes it **verbatim** while `to_canonical_bytes`
280//! **recomputes** it. Use it when you want to *inspect or preserve* the on-wire value (dual-use:
281//! send a deliberately-wrong checksum) yet still be able to emit the correct one. This is what
282//! makes a message [canonical-bearing](#two-encode-forms-verbatim-vs-canonical).
283//!
284//! # Two encode forms: verbatim vs canonical
285//!
286//! A dual-use codec needs to do two opposite things: reproduce a message **exactly** (even a
287//! malformed one you parsed off the wire), and emit a **spec-clean** one. So `#[bin]` gives
288//! you both, and *never silently* picks for you:
289//!
290//! - **`to_bytes()` is verbatim** — it writes exactly what's stored. Retained `reserved` bits
291//! stay, a stored `calc` value is written as-is. This is the faithful inverse of `decode`:
292//! `decode` then `to_bytes` is byte-for-byte identical.
293//! - **`to_canonical_bytes()` is canonical** — `reserved` fields are written as their spec
294//! value and `calc` fields are recomputed, so the result is always spec-compliant.
295//!
296//! The two differ only when a message has a `reserved` or non-`temp` `calc` field — so
297//! `to_canonical_bytes` (and the three helpers below) are generated **only then**; otherwise
298//! verbatim *is* canonical and only `to_bytes` exists. (`temp` + `calc` fields are never
299//! stored, so they always recompute — they don't create a verbatim/canonical gap.)
300//!
301//! Three helpers inspect or normalize the value **in memory**, without encoding:
302//! `is_canonical()`, `canonical_diff()` (the names of the fields that differ from canonical),
303//! and `to_canonical(self) -> Self`.
304//!
305//! ## The `encode_mode` field
306//!
307//! Such a message also carries a wire-ignored **`encode_mode`** (defaulting to `Verbatim`),
308//! settable via `set_encode_mode`/`with_encode_mode` or the builder's `.encode_mode(…)`, and
309//! readable with `encode_mode()`. **Exactly one entry point consults it** — the std-writer
310//! [`encode`](crate::EncodeExt::encode), so you set the policy once and stream the value
311//! without re-specifying. Every *other* encoder ignores it and is explicit: `to_bytes` /
312//! `bit_encode` are always verbatim, `to_canonical_bytes` / `canonical_bit_encode` always
313//! canonical. The mode is **excluded from `PartialEq`/`Eq`/`Hash`/`Debug`** (it's a render
314//! preference, not message data), and because the field can't appear in a struct literal,
315//! **construct these via the builder, `new(…)`, or `decode`** (every `#[bin]` type gets a
316//! positional `new(fields…)` over its stored fields). The injected field has one more
317//! consequence: a `reserved`/`calc` message **rejects serde derives** (`EncodeMode` implements
318//! no `Serialize`), while a plain `#[bin]` message coexists with them fine — one type can
319//! carry both codecs (see `tests/serde_compat.rs`; bnb is deliberately *not* a serde data
320//! format, whose model has no bit widths or byte order).
321//!
322//! ```
323//! use bnb::{bin, EncodeExt, EncodeMode};
324//!
325//! #[bin(big)]
326//! #[derive(Debug, Clone, PartialEq)]
327//! struct Packet {
328//! tag: u8,
329//! #[reserved]
330//! rsv: u8, // spec value 0
331//! #[bw(calc = self.tag ^ 0x5A)]
332//! #[builder(default)]
333//! check: u8, // canonical value: tag ^ 0x5A
334//! }
335//!
336//! // A value a peer sent us with non-spec reserved bits and a stale checksum (builder-only):
337//! let p = Packet::builder().tag(0x10).rsv(0xFF).check(0x99).build().unwrap();
338//!
339//! // VERBATIM — exactly what's stored (so decode -> to_bytes round-trips):
340//! assert_eq!(p.to_bytes().unwrap(), [0x10, 0xFF, 0x99]);
341//!
342//! // CANONICAL — reserved -> 0, checksum recomputed (0x10 ^ 0x5A = 0x4A):
343//! assert_eq!(p.to_canonical_bytes().unwrap(), [0x10, 0x00, 0x4A]);
344//!
345//! // Inspect the gap without encoding:
346//! assert!(!p.is_canonical());
347//! assert_eq!(p.canonical_diff(), ["rsv", "check"]);
348//!
349//! // `encode(w)` follows the value's mode (default Verbatim); set it to stream canonical:
350//! let mut out: Vec<u8> = Vec::new();
351//! p.clone().with_encode_mode(EncodeMode::Canonical).encode(&mut out).unwrap();
352//! assert_eq!(out, [0x10, 0x00, 0x4A]);
353//!
354//! // The mode never affects equality — a value differs from its re-moded self only in render:
355//! assert_eq!(p, p.clone().with_encode_mode(EncodeMode::Canonical));
356//! ```
357//!
358//! See [`directives`](super::directives) for every field directive, and
359//! [`io`](super::io) for decoding from a socket or file rather than a slice. The
360//! `examples/bin_message.rs` example in the repository is a runnable version of the
361//! header + frame above.