macro_rules! bitfield {
(
$(
struct $name:ident {
$(
$field_name:ident: $field_type:ty $(, $bits:literal)?
),* $(,)?
}
)+
) => { ... };
(
struct $name:ident {
$(
$field_name:ident: $field_type:ty $(, $bits:literal)?
),* $(,)?
}
) => { ... };
(@single $name:ident { $($field_name:ident: $field_type:ty $(, $bits:literal)?),* }) => { ... };
(@field_type $field_type:ty, $bits:literal) => { ... };
(@field_type $field_type:ty) => { ... };
(@write_field_to_data $self:ident, $field_name:ident, $field_type:ty, $current_bit:ident, $bits:literal) => { ... };
(@write_field_to_data $self:ident, $field_name:ident, $field_type:ty, $current_bit:ident) => { ... };
(@read_field_from_data $self:ident, $field_name:ident, $field_type:ty, $current_bit:ident, $bits:literal) => { ... };
(@read_field_from_data $self:ident, $field_name:ident, $field_type:ty, $current_bit:ident) => { ... };
(@size $field_type:ty, $bits:literal) => { ... };
(@size $field_type:ty) => { ... };
}Expand description
Macro for defining bitfield structures with automatic serialization support.
§Usage
use rust_bitfield_serializer::*;
bitfield! {
struct MyBitfield {
field1: u8, 4,
field2: u8, 4,
}
}§Examples
use rust_bitfield_serializer::*;
bitfield! {
struct MyBitfield {
field1: u8, 4,
field2: u8, 4,
}
}
let mut bf = MyBitfield::new();
bf.field1 = 0xA;
bf.field2 = 0xB;
let bytes = bf.serialize();
assert_eq!(bytes, vec![0xAB]);
let bf2 = MyBitfield::deserialize(&bytes).unwrap();
assert_eq!(bf2.field1, 0xA);
assert_eq!(bf2.field2, 0xB);Nested structures example:
use rust_bitfield_serializer::*;
bitfield! {
struct NestedHeader {
version: u8, 4,
flags: u8, 4,
}
struct NestedPacket {
header: NestedHeader,
payload_len: u16, 12,
checksum: u8, 8,
}
}
let mut p = NestedPacket::new();
p.header.version = 2;
p.header.flags = 0xF;
p.payload_len = 0xABC;
p.checksum = 0x1;
let bytes = p.serialize();
let p2 = NestedPacket::deserialize(&bytes).unwrap();
assert_eq!(p2.header.version, 2);
assert_eq!(p2.header.flags, 0xF);
assert_eq!(p2.payload_len, 0xABC);
assert_eq!(p2.checksum, 0x1);This creates a struct MyBitfield with fields that can be accessed directly,
along with serialization and deserialization capabilities.
§Multiple Structures
You can define multiple structures in a single macro invocation:
use rust_bitfield_serializer::*;
bitfield! {
struct Header {
version: u8, 4,
flags: u8, 4,
}
struct Packet {
header: Header,
payload_len: u16, 12,
checksum: u8, 8,
}
}§Nested Structures
Bitfield structures can contain other bitfield structures as fields. When no bit count is specified, the entire nested structure is used.