Macro bitflags::bitflags

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

        $($t:tt)*
    ) => { ... };
    (
        $(#[$outer:meta])*
        impl $BitFlags:ident: $T:ty {
            $(
                $(#[$inner:ident $($args:tt)*])*
                const $Flag:tt = $value:expr;
            )*
        }

        $($t:tt)*
    ) => { ... };
    () => { ... };
}
Expand description

Generate a flags type.

§struct mode

A declaration that begins with $vis struct will generate a struct for a flags type, along with methods and trait implementations for it. The body of the declaration defines flags as constants, where each constant is a flags value of the generated flags type.

§Examples

Generate a flags type using u8 as the bits type:

bitflags! {
    struct Flags: u8 {
        const A = 1;
        const B = 1 << 1;
        const C = 0b0000_0100;
    }
}

Flags types are private by default and accept standard visibility modifiers. Flags themselves are always public:

bitflags! {
    pub struct Flags: u8 {
        // Constants are always `pub`
        const A = 1;
    }
}

Flags may refer to other flags using their Flags::bits value:

bitflags! {
    struct Flags: u8 {
        const A = 1;
        const B = 1 << 1;
        const AB = Flags::A.bits() | Flags::B.bits();
    }
}

A single bitflags invocation may include zero or more flags type declarations:

bitflags! {}

bitflags! {
    struct Flags1: u8 {
        const A = 1;
    }

    struct Flags2: u8 {
        const A = 1;
    }
}

§impl mode

A declaration that begins with impl will only generate methods and trait implementations for the struct defined outside of the bitflags macro.

The struct itself must be a newtype using the bits type as its field.

The syntax for impl mode is identical to struct mode besides the starting token.

§Examples

Implement flags methods and traits for a custom flags type using u8 as its underlying bits type:

struct Flags(u8);

bitflags! {
    impl Flags: u8 {
        const A = 1;
        const B = 1 << 1;
        const C = 0b0000_0100;
    }
}

§Named and unnamed flags

Constants in the body of a declaration are flags. The identifier of the constant is the name of the flag. If the identifier is _, then the flag is unnamed. Unnamed flags don’t appear in the generated API, but affect how bits are truncated.

§Examples

Adding an unnamed flag that makes all bits known:

bitflags! {
    struct Flags: u8 {
        const A = 1;
        const B = 1 << 1;

        const _ = !0;
    }
}

Flags types may define multiple unnamed flags:

bitflags! {
    struct Flags: u8 {
        const _ = 1;
        const _ = 1 << 1;
    }
}