#[allow(unused_macros)]
macro_rules! flags {
(
$(#[$meta:meta])*
$vis:vis struct $name:ident: $ty:ty {
$(
$(#[$flag_meta:meta])*
const $flag:ident = $value:expr;
)*
}
) => {
$(#[$meta])*
#[derive(Clone, Copy, PartialEq, Eq, Hash, Default)]
$vis struct $name($ty);
#[allow(dead_code)]
impl $name {
$(
$(#[$flag_meta])*
pub const $flag: Self = Self($value);
)*
#[inline]
pub const fn empty() -> Self {
Self(0)
}
#[inline]
pub const fn is_empty(self) -> bool {
self.0 == 0
}
#[inline]
pub const fn contains(self, other: Self) -> bool {
self.0 & other.0 == other.0
}
#[inline]
pub const fn intersects(self, other: Self) -> bool {
self.0 & other.0 != 0
}
#[inline]
pub const fn union(self, other: Self) -> Self {
Self(self.0 | other.0)
}
#[inline]
pub const fn difference(self, other: Self) -> Self {
Self(self.0 & !other.0)
}
#[inline]
pub(crate) const fn bits(self) -> $ty {
self.0
}
}
impl core::ops::BitOr for $name {
type Output = Self;
#[inline]
fn bitor(self, other: Self) -> Self {
Self(self.0 | other.0)
}
}
impl core::ops::BitOrAssign for $name {
#[inline]
fn bitor_assign(&mut self, other: Self) {
self.0 |= other.0;
}
}
impl core::ops::BitAnd for $name {
type Output = Self;
#[inline]
fn bitand(self, other: Self) -> Self {
Self(self.0 & other.0)
}
}
impl core::ops::Sub for $name {
type Output = Self;
#[inline]
fn sub(self, other: Self) -> Self {
Self(self.0 & !other.0)
}
}
impl core::fmt::Debug for $name {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
f.write_str(concat!(stringify!($name), "("))?;
let mut first = true;
$(
if Self::$flag.0 != 0 && self.contains(Self::$flag) {
if !first {
f.write_str(" | ")?;
}
first = false;
f.write_str(stringify!($flag))?;
}
)*
let _ = first;
f.write_str(")")
}
}
};
}
#[allow(unused_imports)]
pub(crate) use flags;
#[cfg(all(test, feature = "alloc"))]
mod tests {
flags! {
struct Test: u32 {
const A = 1;
const B = 2;
const AB = 3;
}
}
#[test]
fn flags() {
let ab = Test::A | Test::B;
assert_eq!(ab, Test::AB);
assert_eq!(ab.bits(), 3);
assert!(ab.contains(Test::A) && !Test::A.contains(ab));
assert!(Test::A.intersects(ab) && !Test::A.intersects(Test::B));
assert_eq!(ab - Test::A, Test::B);
assert_eq!(ab & Test::A, Test::A);
assert!(Test::empty().is_empty() && Test::default().is_empty());
assert_eq!(alloc::format!("{:?}", Test::A), "Test(A)");
assert_eq!(alloc::format!("{ab:?}"), "Test(A | B | AB)");
assert_eq!(alloc::format!("{:?}", Test::empty()), "Test()");
}
}