Skip to main content

packed_struct

Macro packed_struct 

Source
macro_rules! packed_struct {
    (
        $(#[$meta:meta])*
        $vis:vis struct $name:ident {
            $(
                $(#[$fmeta:meta])*
                $fvis:vis $field:ident : $ty:ty = $bits:expr
            ),+ $(,)?
        }
    ) => { ... };
}
Expand description

Declare a bit-packed struct and implement Encode and Decode for it.

Syntax: an ordinary struct definition in which every field is followed by = <width in bits>. Attributes, doc comments, and visibility on the struct and on each field are passed through. Fields are packed in declaration order, most-significant bit first, using BitWriter / BitReader.

The macro adds two associated constants, BITS (total field width) and SIZE (encoded bytes), and two convenience methods, pack and unpack, that work on a [u8; SIZE] array. See the packed module for the full rules.

§Example

use wire_codec::packed_struct;

packed_struct! {
    #[derive(Debug, Clone, Copy, PartialEq, Eq)]
    pub struct Sample {
        pub valid: bool = 1,
        pub channel: u8 = 3,
        pub delta: i16 = 12,
    }
}

let sample = Sample { valid: true, channel: 5, delta: -2 };
let bytes = sample.pack().unwrap();
assert_eq!(bytes, [0b1_101_1111, 0b1111_1110]);
assert_eq!(Sample::unpack(&bytes).unwrap(), sample);

A field wider than its type does not compile:

ⓘ
wire_codec::packed_struct! {
    struct Bad { x: u8 = 9 }
}