Macro bitflags::bitflags [] [src]

macro_rules! bitflags {
    (
        $(#[$outer:meta])*
        pub struct $BitFlags:ident: $T:ty {
            $(
                $(#[$inner:ident $($args:tt)*])*
                const $Flag:ident = $value:expr;
            )+
        }
    ) => { ... };
    (
        $(#[$outer:meta])*
        struct $BitFlags:ident: $T:ty {
            $(
                $(#[$inner:ident $($args:tt)*])*
                const $Flag:ident = $value:expr;
            )+
        }
    ) => { ... };
}

The macro used to generate the flag structure.

See the crate level docs for complete documentation.

Example

#[macro_use]
extern crate bitflags;

bitflags! {
    struct Flags: u32 {
        const FLAG_A       = 0b00000001;
        const FLAG_B       = 0b00000010;
        const FLAG_C       = 0b00000100;
        const FLAG_ABC     = Self::FLAG_A.bits
                           | Self::FLAG_B.bits
                           | Self::FLAG_C.bits;
    }
}

fn main() {
    let e1 = Flags::FLAG_A | Flags::FLAG_C;
    let e2 = Flags::FLAG_B | Flags::FLAG_C;
    assert_eq!((e1 | e2), Flags::FLAG_ABC);   // union
    assert_eq!((e1 & e2), Flags::FLAG_C);     // intersection
    assert_eq!((e1 - e2), Flags::FLAG_A);     // set difference
    assert_eq!(!e2, Flags::FLAG_A);           // set complement
}

The generated structs can also be extended with type and trait implementations:

#[macro_use]
extern crate bitflags;

use std::fmt;

bitflags! {
    struct Flags: u32 {
        const FLAG_A   = 0b00000001;
        const FLAG_B   = 0b00000010;
    }
}

impl Flags {
    pub fn clear(&mut self) {
        self.bits = 0;  // The `bits` field can be accessed from within the
                        // same module where the `bitflags!` macro was invoked.
    }
}

impl fmt::Display for Flags {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "hi!")
    }
}

fn main() {
    let mut flags = Flags::FLAG_A | Flags::FLAG_B;
    flags.clear();
    assert!(flags.is_empty());
    assert_eq!(format!("{}", flags), "hi!");
    assert_eq!(format!("{:?}", Flags::FLAG_A | Flags::FLAG_B), "FLAG_A | FLAG_B");
    assert_eq!(format!("{:?}", Flags::FLAG_B), "FLAG_B");
}