Skip to main content

bitframe/
lib.rs

1//! # bitframe
2//!
3//! Macro-driven bit-level packet formats with zero-copy parsing.
4//!
5//! `bitframe` generates zero-copy **view types** over `&[u8]` from annotated struct
6//! definitions. Each field is read on demand directly from the byte buffer — no
7//! allocation, no copying.
8//!
9//! # Quick start
10//!
11//! ```
12//! use bitframe::prelude::*;
13//!
14//! #[bitframe]
15//! pub struct SensorReading {
16//!     pub tag:    u4,
17//!     pub flags:  u4,
18//!     pub value:  u16,
19//! }
20//!
21//! let bytes = [0xA5, 0x00, 0x0A];
22//! let (reading, _rest) = SensorReadingRef::parse(&bytes)?;
23//!
24//! assert_eq!(reading.tag().value(), 0xA);
25//! assert_eq!(reading.flags().value(), 0x5);
26//! assert_eq!(reading.value(), 10u16);
27//! # Ok::<(), bitframe::Error>(())
28//! ```
29//!
30//! # Using `Parseable` in generic code
31//!
32//! ```
33//! use bitframe::prelude::*;
34//!
35//! fn parse_and_report<'a, T: Parseable<'a>>(bytes: &'a [u8]) -> Result<T::View, Error>
36//! where
37//!     T::View: core::fmt::Debug,
38//! {
39//!     let (view, rest) = T::parse(bytes)?;
40//!     // rest contains any bytes beyond the layout
41//!     Ok(view)
42//! }
43//!
44//! #[bitframe]
45//! pub struct MyHeader {
46//!     pub version: u4,
47//!     pub length:  u12,
48//! }
49//!
50//! let bytes = [0x10, 0x0A];
51//! let header = parse_and_report::<MyHeader>(&bytes)?;
52//! assert_eq!(header.version().value(), 1);
53//! assert_eq!(header.length().value(), 10);
54//! # Ok::<(), bitframe::Error>(())
55//! ```
56//!
57//! # Bit-sized types
58//!
59//! Types `u1`..`u63` (skipping `u8`, `u16`, `u32`, `u64`) represent unsigned
60//! integers narrower than their backing storage. See the [`types`] module for details.
61
62#![cfg_attr(not(feature = "std"), no_std)]
63#![forbid(unsafe_code)]
64
65pub mod error;
66pub mod traits;
67pub mod types;
68
69pub use bitframe_derive::{bitframe, bitframe_enum};
70pub use error::Error;
71pub use types::OutOfRange;
72
73/// Re-exports everything needed for typical `bitframe` usage.
74///
75/// ```
76/// use bitframe::prelude::*;
77///
78/// let v = u3::new(7);
79/// assert_eq!(v, 7u8);
80/// ```
81pub mod prelude {
82    pub use crate::error::Error;
83    pub use crate::traits::{BitLayout, Parseable};
84    pub use crate::types::{
85        u1, u10, u11, u12, u13, u14, u15, u17, u18, u19, u2, u20, u21, u22, u23, u24, u25, u26,
86        u27, u28, u29, u3, u30, u31, u33, u34, u35, u36, u37, u38, u39, u4, u40, u41, u42, u43,
87        u44, u45, u46, u47, u48, u49, u5, u50, u51, u52, u53, u54, u55, u56, u57, u58, u59, u6,
88        u60, u61, u62, u63, u7, u9, OutOfRange,
89    };
90    pub use bitframe_derive::{bitframe, bitframe_enum};
91}