
simple_bitfield - yet another bitfield implementation for Rust
Easily create C-style bitfields that have the same size as the underlying type and are Copy + Clone (requires the underlying type to be Copy + Clone as well):
use simple_bitfield::{bitfield, Field};
bitfield! {
struct MyBitfield<u32> {
field1: 3, field2: 9,
_: 6, field3: 1 }
struct AnotherBitfield<u8> {
_: 7,
highest_bit: 1
}
}
fn main() {
let mut a_bitfield = MyBitfield::new(12345);
let field3: u32 = a_bitfield.field3.get();
println!(
"{:#b} => {:#b}, {:#b}, {:#b}",
u32::from(a_bitfield), field3,
a_bitfield.field2.get(),
a_bitfield.field1.get()
);
a_bitfield.field1.set(0);
println!("{:#b}", u32::from(a_bitfield));
let another_one: AnotherBitfield::AnotherBitfield = AnotherBitfield::new(184);
let another_one_highest: &AnotherBitfield::highest_bit = &another_one.highest_bit;
println!("{:#b}", another_one_highest.get())
}
Syntax
Like in C:
(pub) struct BitfieldName<BaseType> {
field_name: field_size,
_: size_to_skip
}
Documentation
On docs.rs: https://docs.rs/simple_bitfield
Credits
Initial idea was adapted from https://guiand.xyz/blog-posts/bitfields.html.