bitbag

Crates.iobitbag
lib.rsbitbag
version0.3.0
sourcesrc
created_at2021-07-31 23:14:54.291036
updated_at2024-11-22 02:15:51.520214
descriptionA useful struct for dealing with bit flags
homepage
repositoryhttps://github.com/aatifsyed/bitbag
max_upload_size
id429846
size23,005
Aatif Syed (aatifsyed)

documentation

https://docs.rs/bitbag

README

crates-io docs-rs github

This crate provides [BitBag], a type intended for tracking bitflags defined in a field-less enum. Get started like this:

#[derive(bitbag::Flags)]
#[repr(u8)]
enum MyFlags {
    A = 0b0001,
    B = 0b0010,
    C = 0b0100,
}

Basic functionality is provided by [Flags]

let mut bag = bitbag::BitBag::<MyFlags>::new_unchecked(0b0011);
assert!(bag.is_set(MyFlags::A));
assert!(bag.is_set(MyFlags::B));
assert!(!bag.is_set(MyFlags::C));

bag.set(MyFlags::C);
assert_eq!(bag.repr(), 0b0111);

Deriving [BitOr] will also give you very ergonomic constructors

#[derive(bitbag::BitOr)]
enum MyFlags { ... }
use MyFlags::*;
let bag = A | B | C;
assert!(bag.is_set(MyFlags::A));
assert!(bag.is_set(MyFlags::B));
assert!(bag.is_set(MyFlags::C));

You can also choose to reject unrecognised bits, and iterate over the set flags.

let e = bitbag::BitBag::<MyFlags>::new_checked(0b1000).unwrap_err();
assert_eq!(e.to_string(), "The bits 0b1000 are not accounted for in MyFlags");

let bag = bitbag::BitBag::<MyFlags>::new_checked(0b0110).unwrap();
for flag in bag {
    match flag {
        MyFlags::A => println!("Flag A was set"),
        MyFlags::B => println!("Flag B was set"),
        MyFlags::C => println!("Flag C was set"),
    }
};
Commit count: 36

cargo fmt