Crates.io | bitbag |
lib.rs | bitbag |
version | 0.3.0 |
source | src |
created_at | 2021-07-31 23:14:54.291036 |
updated_at | 2024-11-22 02:15:51.520214 |
description | A useful struct for dealing with bit flags |
homepage | |
repository | https://github.com/aatifsyed/bitbag |
max_upload_size | |
id | 429846 |
size | 23,005 |
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"),
}
};