6 releases

0.2.1 Mar 10, 2023
0.1.4 Aug 3, 2021
0.1.0 Jul 31, 2021

#1005 in Rust patterns

MIT license

25KB
582 lines

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"),
    }
};

Dependencies

~5–15MB
~169K SLoC