Skip to main content

bnb/
lib.rs

1/*!
2`bnb` — an owned, bit-aware binary codec: ergonomic, fast bit/byte field types and
3the unified `#[bin]` whole-message codec.
4
5It provides, designed to *compose*:
6
7- **Arbitrary-width integers** ([`u1`]..[`u127`], via [`UInt`]) for sub-byte
8  fields — a dependency-free replacement for `arbitrary-int`.
9- **`#[bitfield]`** — an attribute macro that packs typed fields into a single
10  backing integer with **explicit, independent control of bit order**
11  (MSB/LSB-first) **and byte order** (big/little). It generates getters,
12  immutable `with_*` setters, raw access, and allocation-free `*_bytes` conversions.
13- **`#[derive(BitEnum)]`** — enum ⇄ integer at a chosen width, with an optional
14  `#[catch_all]` variant that preserves unknown values (the dual-use convention).
15- **`#[bin]`** — the unified whole-message codec (see below): reads/writes a struct
16  at arbitrary bit offsets, with a rich, `binrw`-inspired directive surface.
17
18The aim is to collapse a whole stack of overlapping helpers —
19`modular-bitfield`(`-msb`), `bitfield-struct`, `bitbybit`, `arbitrary-int`,
20`num_enum`, and a `binrw`-style codec — into one fast, integer-backed
21(shift/mask, no `bitvec`) crate. See [Inspiration](#inspiration).
22
23# Example — a DNS-style 16-bit header field
24
25```
26use bnb::{bitfield, BitEnum, u4, u5, u7};
27
28# #[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
29# struct Flags(bnb::u7);
30# impl bnb::Bits for Flags {
31#     const BITS: u32 = 7;
32#     fn into_bits(self) -> u128 { self.0.into_bits() }
33#     fn from_bits(raw: u128) -> Self { Flags(u7::from_bits(raw)) }
34# }
35#[derive(BitEnum, Clone, Copy, Debug, PartialEq, Eq)]
36#[bit_enum(u4)]
37enum RCode {
38    NoError,   // 0
39    FormErr,   // 1
40    ServFail,  // 2
41    #[catch_all]
42    Other(u4), // any other 4-bit value
43}
44
45// MSB-first packing (network/RFC order), big-endian on the wire.
46#[bitfield(u16, bits = msb, bytes = be)]
47#[derive(Clone, Copy, Debug, PartialEq, Eq)]
48struct State {
49    opcode: u5,   // first field -> high bits
50    flags:  Flags,
51    rcode:  RCode, // last field -> low bits
52}
53
54let s = State::new()
55    .with_opcode(u5::new(2))
56    .with_rcode(RCode::ServFail);
57assert_eq!(s.rcode(), RCode::ServFail);
58// opcode occupies bits 11..=15 (the high 5 of the u16).
59assert_eq!(s.to_be_bytes()[0] >> 3, 2);
60```
61
62# Bit order vs. byte order
63
64These are independent knobs, which is the whole point:
65
66- `bits = msb | lsb` — does the **first** declared field land in the high or low
67  bits of the backing integer. Default: `msb` (matches RFC ASCII-art layouts).
68- `bytes = be | le` — endianness of the backing integer when serialized.
69  Default: `be`.
70
71# The `#[bin]` codec
72
73Whole-message bit-aware codec: `#[bin]` (magic/count/ctx/map/if/calc·temp/reserved/
74positioning/validate) over a `Source`/`SeekSource`/`BufSource`/`SeekReader` I/O
75ladder, with an opt-in `bytes` feature for async framing.
76
77# Feature flags & `no_std`
78
79`bnb` is `no_std`-compatible — it always needs `alloc` (the codec produces
80`Vec<u8>` and owns variable-length payloads), but not `std`. Build with
81`default-features = false` for an embedded target.
82
83- **`std`** *(default)* — the `std::io` ladder ([`StreamBitReader`], [`BufSource`],
84  [`SeekReader`], [`Source::as_read`]/[`Sink::as_write`]), the `From<std::io::Error>`
85  bridge, and the `encode(writer)`/`spec_encode(writer)` conveniences ([`EncodeExt`]/
86  [`SpecEncodeExt`]). The `#[br(dbg)]` directive (which emits a `tracing` event) is
87  also `std`-only.
88- **`bytes`** — the zero-copy `bytes`-crate adapters; implies `std` (async/tokio framing).
89
90Without `std` you still get the full macro surface plus: decode from a `&[u8]`
91([`BitReader`], `Type::decode`/`decode_exact`/`peek`/`decode_from`) and encode to a
92`Vec<u8>` (`Type::to_bytes`/`to_spec_bytes`, `encode_into` over a [`Sink`]). You lose
93only the streaming `std::io` adapters and `encode(&mut impl Write)`; on `no_std`,
94encode with `to_bytes()` and write the bytes to your transport yourself.
95
96# Inspiration
97
98`bnb` stands on the shoulders of several excellent crates, collapsing their
99capabilities into one: the arbitrary-width integers of `arbitrary-int`; the
100bitfield packing of `modular-bitfield`, `bitfield-struct`, and `bitbybit`; the
101enum ⇄ integer mapping of `num_enum`; and — most of all — the declarative,
102bidirectional codec design of [`binrw`](https://github.com/jam1garner/binrw),
103whose `#[br]`/`#[bw]` attribute vocabulary `#[bin]` deliberately echoes so the two
104feel like one toolkit. `bnb` shares no code with these crates; it is a from-scratch
105implementation, extended to do the one thing a byte-oriented `Read + Seek` codec
106cannot: read and write fields at arbitrary **bit** offsets. See `ACKNOWLEDGMENTS.md`
107for the full credit.
108
109# Guide
110
111The [`guide`] module is a set of worked, runnable walkthroughs — start there for a
112tour of the crate and the rationale behind each piece. Reading order:
113
1141. [`guide::quick_start`] — a five-minute tour of every macro.
1152. [`guide::numbers`] — the arbitrary-width integers (`u1`..`u127`) and the [`Bits`]
116   trait that lets everything compose.
1173. [`guide::bitfields`] — `#[bitfield]`: bit order, byte order, widths and ranges,
118   nesting.
1194. [`guide::enums`] — `#[derive(BitEnum)]`: catch-all vs. closed, `num_enum` parity.
1205. [`guide::flags`] — `#[bitflags]`: single-bit flag sets with set algebra.
1216. [`guide::builders`] — `#[derive(BitsBuilder)]`: the required-by-default builder.
1227. [`guide::bin_codec`] — `#[bin]`: a whole protocol header, end to end.
1238. [`guide::directives`] — the field-directive reference, one example each.
1249. [`guide::dispatch`] — `#[bin]` on an enum: tagged-union dispatch by wire `magic` or off-wire `tag`.
12510. [`guide::io`] — the `Source`/`Sink` I/O ladder (slice, stream, socket, file, `bytes`).
12611. [`guide::errors`] — position-aware errors and the streaming `Incomplete` signal.
12712. [`guide::dual_use`] — the compliant-by-default-but-violatable philosophy.
12813. [`guide::composition`] — how the pieces nest and size each other.
129*/
130
131// Every public item must be documented (the `uN` aliases are the one self-
132// evident exception, allowed at their module).
133#![deny(missing_docs)]
134// `bnb` is `no_std` when built without the (default) `std` feature; `alloc` is
135// always required — the codec produces `Vec<u8>` and owns variable-length
136// payloads/error messages. The `std` feature re-enables the `std::io` ladder
137// (`StreamBitReader`/`BufSource`/`SeekReader`, `encode(writer)`).
138#![cfg_attr(not(feature = "std"), no_std)]
139
140extern crate alloc;
141// Macro-generated code references the runtime by the path `proc-macro-crate`
142// resolves — `::bnb` for the crate itself. This self-alias makes that path
143// resolve inside the crate's own modules (the lib name is `bnb`).
144extern crate self as bnb;
145
146pub mod bitstream;
147pub mod builder;
148pub mod error;
149mod field;
150pub mod guide;
151pub mod int;
152
153pub use bitstream::{
154    BitAmount, BitDecode, BitEncode, BitError, BitReader, BitWriter, DecodeWith, EncodeWith,
155    ErrorKind, FixedBitLen, Layout, SeekSource, Sink, Source, SpecEncode,
156};
157
158/// The `std::io` I/O ladder and writer conveniences — only with the (default)
159/// `std` feature. Without it, `bnb` is `no_std + alloc`: decode from a `&[u8]`
160/// (`BitReader`), encode to a `Vec<u8>` (`to_bytes`/`to_spec_bytes`).
161#[cfg(feature = "std")]
162pub use bitstream::{
163    BufSource, EncodeExt, SeekReader, SinkWriter, SourceReader, SpecEncodeExt, StreamBitReader,
164};
165
166/// Zero-copy `bytes`-crate adapters (the `bytes` feature).
167#[cfg(feature = "bytes")]
168pub use bitstream::{BytesReader, BytesWriter};
169
170/// Common imports for the codec — the typed positioning amounts (`4.bits()`,
171/// `3.bytes()`) used by `#[br(pad_before = …)]` etc., plus the encode extension
172/// traits that carry `encode(writer)`/`spec_encode(writer)` (the `std` feature).
173pub mod prelude {
174    pub use crate::BitAmount;
175    #[cfg(feature = "std")]
176    pub use crate::{EncodeExt, SpecEncodeExt};
177}
178pub use builder::BuilderError;
179pub use error::{Error, Result, UnknownDiscriminant};
180pub use field::{BitOrder, Bitfield, Bits, ByteOrder};
181pub use int::{UInt, *};
182
183// Re-export the macros so users depend only on `bnb`. A derive macro and a
184// trait may share a name (like `Debug`) — they live in different namespaces —
185// so `BitEnum`/`BitDecode`/`BitEncode` are each both a derive and a trait.
186pub use bnb_macros::{BitDecode, BitEncode, BitEnum, BitsBuilder, bin, bitfield, bitflags};
187
188/// Marker trait implemented by `#[derive(BitEnum)]` enums: a [`Bits`] value
189/// whose representation is an integer discriminant of a fixed width.
190pub trait BitEnum: Bits {}
191
192/// Implementation details referenced by macro-generated code. Not a stable API.
193#[doc(hidden)]
194pub mod __private {
195    pub use crate::bitstream::{
196        BitDecode, BitEncode, BitError, BitReader, BitWriter, FixedBitLen, Layout, SeekSource,
197        Sink, Source, align_read, align_write, bits_of, decode_consume, decode_exact,
198        decode_exact_with, decode_peek, decode_peek_with, encode_to_vec, encode_to_vec_with,
199        peek_bytes, read_byte_array, read_mapped, read_try_mapped, skip_read, skip_write,
200        verify_magic, write_byte_array, write_mapped,
201    };
202    /// The `std::io::Write`-based encode helpers, behind the `std` feature.
203    #[cfg(feature = "std")]
204    pub use crate::bitstream::{encode_to_writer, encode_to_writer_with};
205    pub use crate::error::UnknownDiscriminant;
206    pub use crate::field::{BitOrder, Bitfield, Bits, ByteOrder};
207    /// Owned-collection re-exports so macro-generated code names neither `std` nor
208    /// `alloc` directly (the user crate need not declare `extern crate alloc`).
209    pub use ::alloc::{string::String, vec, vec::Vec};
210    /// Re-exported for the `#[br(dbg)]` directive's generated `trace!` call, so a user
211    /// of the directive needs no direct `tracing` dependency. `#[br(dbg)]` is a
212    /// `std`-only debugging aid (see the `tracing` dependency note in `Cargo.toml`).
213    #[cfg(feature = "std")]
214    pub use ::tracing;
215}