Expand description
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.as_ref(), 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"),
}
};
Structs
- Wraps a primitive, with helper methods for checking flags.
AsRef
s to the primitive if you wish to access it - The error returned when calling a
BitBag
from a primitive which contains bits set which aren’t represented by flags - The error returned when calling
BitBag::check_nonoverlapping
Traits
- The trait that allows an item to be placed inside a
BitBag
.
Derive Macros
- Derives BitBaggable and [
BitOr
] for a field-less enum. - Derives a new BoolBag struct for a field-less enum