Skip to main content

bitflagset

Macro bitflagset 

Source
macro_rules! bitflagset {
    (@ops $name:ident, $repr:ty) => { ... };
    ($vis:vis struct $name:ident($repr:ty) : $typ:ty) => { ... };
    ($vis:vis struct $name:ident($repr:ty) {
        $($(#[$inner:meta])* const $flag:ident = $value:expr;)*
    }) => { ... };
}
Expand description

Generates a newtype bitset backed by a primitive integer.

Two forms are supported:

§Enum form

Wraps an existing #[repr(u8)] enum whose variants map 1:1 to bit positions. The element type is the enum itself.

bitflagset::bitflagset!(pub struct MySet(u8) : MyEnum);

Requirements:

  • The enum must be #[repr(u8)] with discriminants that fit in the storage primitive (e.g. 0..7 for u8, 0..63 for u64).
  • TryFrom<u8> must be implemented for the enum.
  • The enum must implement BitFlag so FLAGS/MAX_VALUE are available for compile-time validation (bitflag! does this automatically).
  • Using [bitflag!] for the enum is optional but convenient. If you do not use it, define the enum manually and implement the required conversions and traits yourself.

§Position form (bitflags-compatible)

Defines named flag constants directly inside the struct, matching the bitflags! macro syntax. The element type is the struct itself.

bitflagset::bitflagset! {
    pub struct MyFlags(u8) {
        const A = 0;
        const B = 1;
        const C = 2;
    }
}

let mut f = MyFlags::empty();
f.insert(MyFlags::A);
f.insert(MyFlags::B);
assert!(f.contains(&MyFlags::A));
assert_eq!(f.len(), 2);

When the bitflags feature is enabled, the generated struct also implements bitflags::Flags.