Bitmask-Enum

A bitmask enum attribute macro, to turn an enum into a bitmask.
A bitmask can have (un)signed integer types, the default type is usize
.
First created because I wanted something simple, evolved with inspiration from
the bitflags crate, which might be something
you want to take a look at.
use bitmask_enum::bitmask;
#[bitmask] enum Bitmask { }
#[bitmask(u8)] enum BitmaskU8 { }
Example
use bitmask_enum::bitmask;
#[bitmask(u8)]
enum Bitmask {
Flag1, Flag2, Flag3, }
impl Bitmask {
fn _set_to(&mut self, val: u8) {
self.bits = val
}
}
const CONST_BM: Bitmask = Bitmask::Flag2.or(Bitmask::Flag3);
fn main() {
println!("{:#010b}", CONST_BM);
let bm = Bitmask::Flag1 | Bitmask::Flag3;
println!("{:#010b}", bm);
println!("{}", bm.intersects(CONST_BM));
println!("{}", bm.contains(CONST_BM)); }
Custom Values
You can assign any flag a custom value.
use bitmask_enum::bitmask;
#[bitmask(u8)]
enum Bitmask {
Flag1,
CustomFlag3 = 0b00000100,
Flag2, Flag3,
Flag13_1 = 0b00000001 | 0b00000100,
Flag13_2 = Self::Flag1.or(Self::Flag3).bits,
Flag13_3 = Self::Flag1.bits | Self::CustomFlag3.bits,
Flag123 = {
let flag13 = Self::Flag13_1.bits;
flag13 | Self::Flag2.bits
},
}
fn main() {
let bm = Bitmask::Flag1 | Bitmask::Flag3;
println!("{:#010b}", bm); println!("{}", bm == Bitmask::Flag13_1);
println!("{:#010b}", Bitmask::Flag123); }
Bitmask Config
It is possible to add custom bitmask config options via the #[bitmask_config(...)]
macro. (Just add it below the #[bitmask]
macro)
use bitmask_enum::bitmask;
#[bitmask(u8)]
#[bitmask_config(inverted_flags)]
enum Bitmask {
Flag1, }
fn main() {
println!("{:#010b}", Bitmask::Flag1); println!("{:#010b}", Bitmask::InvertedFlag1); }
Available Config Options
inverted_flags
=> Adds an inverted flag for every non-inverted flag to the bitmask.
If you need / can think of any other config option, feel free to suggest them and we can discuss implementing them.
Implemented Methods
const fn bits(&self) -> #type {
const fn all() -> Self;
const fn is_all(&self) -> bool;
const fn none() -> Self;
const fn is_none(&self) -> bool;
const fn intersects(&self, other: Self) -> bool;
const fn contains(&self, other: Self) -> bool;
const fn not(self) -> Self;
const fn and(self, other: Self) -> Self;
const fn or(self, other: Self) -> Self;
const fn xor(self, other: Self) -> Self;
Implemented Traits
#[repr(transparent)]
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
impl core::ops::Not;
impl core::ops::BitAnd;
impl core::ops::BitAndAssign;
impl core::ops::BitOr;
impl core::ops::BitOrAssign;
impl core::ops::BitXor;
impl core::ops::BitXorAssign;
impl From<#type> for #ident;
impl From<#ident> for #type;
impl PartialEq<#type>;
impl core::fmt::Binary;
impl core::fmt::LowerHex;
impl core::fmt::UpperHex;
impl core::fmt::Octal;