use bnb::{BitOrder, BitReader, BitWriter, ByteOrder, Layout, bin, u4};
#[bin(big)]
#[derive(Debug, PartialEq)]
struct WordBe {
v: u32,
}
#[bin(little)]
#[derive(Debug, PartialEq)]
struct WordLe {
v: u32,
}
#[bin(big, bit_order = msb)]
#[derive(Debug, PartialEq)]
struct NibblesMsb {
a: u4,
b: u4,
}
#[bin(big, bit_order = lsb)]
#[derive(Debug, PartialEq)]
struct NibblesLsb {
a: u4,
b: u4,
}
#[bin(big, bit_order = msb)]
#[derive(Debug, PartialEq)]
struct BeMsb {
hi: u4,
lo: u4,
word: u16,
}
#[bin(little, bit_order = msb)]
#[derive(Debug, PartialEq)]
struct LeMsb {
hi: u4,
lo: u4,
word: u16,
}
#[bin(big, bit_order = lsb)]
#[derive(Debug, PartialEq)]
struct BeLsb {
hi: u4,
lo: u4,
word: u16,
}
#[bin(little, bit_order = lsb)]
#[derive(Debug, PartialEq)]
struct LeLsb {
hi: u4,
lo: u4,
word: u16,
}
fn main() {
assert_eq!(
WordBe { v: 0x1234_5678 }.to_bytes().unwrap(),
[0x12, 0x34, 0x56, 0x78]
);
assert_eq!(
WordLe { v: 0x1234_5678 }.to_bytes().unwrap(),
[0x78, 0x56, 0x34, 0x12]
);
println!("byte order: big = 12 34 56 78 little = 78 56 34 12 (same u32)");
let (a, b) = (u4::new(0xA), u4::new(0xB));
assert_eq!(NibblesMsb { a, b }.to_bytes().unwrap(), [0xAB]);
assert_eq!(NibblesLsb { a, b }.to_bytes().unwrap(), [0xBA]);
println!("bit order: msb = AB lsb = BA (same nibbles a=A, b=B)");
macro_rules! corner {
($T:ident) => {{
let v = $T {
hi: u4::new(0xA),
lo: u4::new(0xB),
word: 0x1234,
};
let bytes = v.to_bytes().unwrap();
assert_eq!($T::decode_exact(&bytes).unwrap(), v); bytes
}};
}
let corners = [
corner!(BeMsb),
corner!(LeMsb),
corner!(BeLsb),
corner!(LeLsb),
];
for i in 0..corners.len() {
for j in (i + 1)..corners.len() {
assert_ne!(corners[i], corners[j], "an axis is aliasing the other");
}
}
println!("independent: all four (bit × byte) corners are distinct and round-trip");
let layout = Layout {
bit: BitOrder::Msb,
byte: ByteOrder::Little,
};
let mut w = BitWriter::with_layout(layout);
w.write(0x1234u16).unwrap();
assert_eq!(w.into_bytes(), [0x34, 0x12]); let mut r = BitReader::with_layout(&[0x34, 0x12], layout);
assert_eq!(r.read::<u16>().unwrap(), 0x1234); println!("low-level: BitWriter/BitReader honor an explicit Layout (msb, little) for a u16");
println!("all checks passed");
}