bit-struct
Bit struct is a crate which allows for ergonomic use of C-like bit fields without mediocre IDE support resulting from proc macros. In addition, everything is statically typed checked!
Take the following example
use *;
enums!
bit_struct!
// We can create a new `HouseConfig` like such:
// where all numbers are statically checked to be in bounds.
let config = new;
// We can get the raw `u8` which represents `config`:
let raw: u8 = config.raw;
assert_eq!;
// or we can get a `HouseConfig` from a `u8` like:
let mut config: HouseConfig = try_from.unwrap;
assert_eq!;
// We need to unwrap because `HouseConfig` is not valid for all numbers. For instance, if the
// most significant bits are `0b11`, it encodes an invalid `HouseKind`. However,
// if all elements of a struct are always valid (suppose we removed the `kind` field), the struct will
// auto implement a trait which allows calling the non-panicking:
// let config: HouseConfig = HouseConfig::exact_from(123_u8);
// We can access values of `config` like so:
let kind: HouseKind = config.kind.get;
// And we can set values like so:
config.lowest_floor.set;
// We can also convert the new numeric types for alternate bit-widths into the
// numeric types provided by the standard library:
let lowest_floor: i3 = config.lowest_floor.get;
let lowest_floor_std: i8 = lowest_floor.value;
assert_eq!;
Benefits
- No proc macros
- Autocompletion fully works (tested in IntelliJ Rust)
- Fast compile times
- Statically checks that structs are not overfilled. For example, these overfilled structs will not compile:
bit_struct::bit_struct! { struct TooManyFieldsToFit(u16) { a: u8, b: u8, c: bit_struct::u1 } }
bit_struct::bit_struct! { struct FieldIsTooBig(u16) { a: u32 } }
- Statically checked types
Further Documentation
Look at the integration tests in the tests
folder for further insight.