Crates.io | const-bitfield |
lib.rs | const-bitfield |
version | 0.2.2 |
source | src |
created_at | 2021-12-27 17:09:56.475261 |
updated_at | 2022-11-29 19:44:27.425653 |
description | Macros for generating bitfield-like structures with const support. |
homepage | |
repository | https://github.com/ppmathis/const-bitfield |
max_upload_size | |
id | 503787 |
size | 58,168 |
This crate provides a bitfield!
macro for generating bitfield-like structures in Rust with support for compile-time
evaluation using const
. The following features are currently supported:
u8
, u16
, u32
, u64
, u128
as backing storage typesbool
From
traitFrom
traitno_std
Unfortunately Rust Stable does not currently contain all required features for implementing this crate. To use of this library, you must use a recent Rust Nightly release and add the following feature flags to your crate root:
#![feature(const_convert)] // optional, when using from/into conversion
#![feature(const_mut_refs)] // always required
#![feature(const_trait_impl)] // always required
Here is a simple example of how this library can be used:
#![feature(const_convert)] // optional, when using from/into conversion
#![feature(const_mut_refs)] // always required
#![feature(const_trait_impl)] // always required
use const_bitfield::bitfield;
bitfield! {
#[derive(Copy, Clone)]
pub struct MyBitField(u32);
u8, hello, set_hello: 6, 0; // hello is stored in bits 0..=6
bool, world, set_world: 7; // world is stored in bit 7
// bits 8..=15 are unused
u16, goodbye, set_goodbye: 31, 16; // goodbye is stored in bits 16..=31
}
fn example() {
let mut bf = MyBitField(0);
bf.set_hello(0b0110110);
bf.set_world(true);
bf.set_goodbye(0xF00F);
println!("{}", bf.hello());
println!("{}", bf.world());
println!("{}", bf.goodbye());
}
A more detailed example can be found within tests/bitfield_gdt.rs which uses the bitfield!
macro
to implement parsing and building entries of the x86 Global Descriptor Table.
You may wish to combine this crate with const-enum to directly map fields of your bitfield
from and into enums with a repr
type. To do so, simply use #[derive(ConstEnum)]
along with e.g. repr(u8)
. This specific use case
is also shown as part of the GDT example linked above.
This crate is heavily inspired by dzamlo/rust-bitfield.
The API between these two crates is similar, but no compatibility is guaranteed.
Unlike the other library, this one focuses on const
-support to allow using it as a helper for complex data structures
at compile-time without having an impact on runtime performance.
Licensed under either of
at your option.
Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the work by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions.