Crates.io | bitbag |
lib.rs | bitbag |
version | 0.2.1 |
source | src |
created_at | 2021-07-31 23:14:54.291036 |
updated_at | 2023-03-10 20:45:41.099918 |
description | A useful struct for dealing with bit flags |
homepage | |
repository | https://github.com/aatifsyed/bitbag |
max_upload_size | |
id | 429846 |
size | 24,072 |
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"),
}
};