bitflags

Macro bitflags_match

Source
macro_rules! bitflags_match {
    ($operation:expr, {
        $($t:tt)*
    }) => { ... };
}
Expand description

A macro that matches flags values, similar to Rust’s match statement.

In a regular match statement, the syntax Flag::A | Flag::B is interpreted as an or-pattern, instead of the bitwise-or of Flag::A and Flag::B. This can be surprising when combined with flags types because Flag::A | Flag::B won’t match the pattern Flag::A | Flag::B. This macro is an alternative to match for flags values that doesn’t have this issue.

§Syntax

bitflags_match!(expression, {
    pattern1 => result1,
    pattern2 => result2,
    ..
    _ => default_result,
})

The final _ => default_result arm is required, otherwise the macro will fail to compile.

§Examples

use bitflags::{bitflags, bitflags_match};

bitflags! {
    #[derive(PartialEq)]
    struct Flags: u8 {
        const A = 1 << 0;
        const B = 1 << 1;
        const C = 1 << 2;
    }
}

let flags = Flags::A | Flags::B;

bitflags_match!(flags, {
    Flags::A | Flags::B => println!("A and/or B are set"),
    _ => println!("neither A nor B are set"),
})

§How it works

The macro expands to a series of if statements, checking equality between the input expression and each pattern. This allows for correct matching of bitflag combinations, which is not possible with a regular match expression due to the way bitflags are implemented.

Patterns are evaluated in order.