bitbag

Crates.iobitbag
lib.rsbitbag
version0.2.1
sourcesrc
created_at2021-07-31 23:14:54.291036
updated_at2023-03-10 20:45:41.099918
descriptionA useful struct for dealing with bit flags
homepage
repositoryhttps://github.com/aatifsyed/bitbag
max_upload_size
id429846
size24,072
Aatif Syed (aatifsyed)

documentation

https://docs.rs/bitbag

README

crates-io docs-rs github

bitbag

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

use bitbag::{BitBag, BitBaggable};
use strum::EnumIter;

#[derive(BitBaggable, EnumIter, Clone, Copy)]
#[repr(u8)]
enum Flags {
    A = 0b0001,
    B = 0b0010,
    C = 0b0100,
}

Basic functionality is provided by [BitBag]

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

bag.set(Flags::C);
assert_eq!(*bag, 0b0111);

Deriving [BitBaggable] will also give you very ergonomic constructors

use Flags::*;
let bag = A | B | C;
assert!(bag.is_set(Flags::A));
assert!(bag.is_set(Flags::B));
assert!(bag.is_set(Flags::C));

Additionally deriving [EnumIter], and [Copy] will allow fallible creation, and iteration over the set flags

//                                  ⬇ this bit is not defined in Flags
let result = BitBag::<Flags>::new(0b1000);
assert!(matches!(
    result,
    Err(e) if e.given() == 0b1000
));

let bag = BitBag::<Flags>::new_unchecked(0b0110);
for flag in &bag {
    match flag {
        Flags::A => println!("Flag A was set"),
        Flags::B => println!("Flag B was set"),
        Flags::C => println!("Flag C was set"),
    }
};
Commit count: 30

cargo fmt