pub trait Packable<B: Buffer> {
const SIZE: u32;
// Required methods
fn pack(&self) -> B;
fn unpack(buffer: B) -> Self;
}Expand description
A type that can be packed into and unpacked from a Buffer of type B.
The #[packable(B)] attribute macro derives this trait
for structs and enums automatically. Implement it manually for primitive
types or for custom encodings.
§Manual implementation contract
packmust return a value where bits at and above positionSIZEare zero. Debug builds verify this withassert!; release builds silently mask oversized values.unpackreceives a value where only the lowerSIZEbits are meaningful; higher bits are not guaranteed to be zero.
§Example
A 5×6 board coordinate packed into 5 bits — fewer than the 6 bits a naive “3 bits for x + 3 bits for y” layout would use:
use bitcram::Packable;
struct Coord { x: u8, y: u8 }
impl Packable<u16> for Coord {
const SIZE: u32 = 5;
fn pack(&self) -> u16 {
(self.y * 5 + self.x) as u16
}
fn unpack(buffer: u16) -> Self {
let i = buffer as u8;
Self { x: i % 5, y: i / 5 }
}
}Required Associated Constants§
Required Methods§
Dyn Compatibility§
This trait is not dyn compatible.
In older versions of Rust, dyn compatibility was called "object safety".