Macro bitpat::bitpat[][src]

macro_rules! bitpat {
    ( @build $relevant:tt $ones:tt [] ) => { ... };
    ( @build $relevant:tt $ones:tt [$next:tt $($rest:tt)*] ) => { ... };
    ( @relevant _ ) => { ... };
    ( @relevant 0 ) => { ... };
    ( @relevant 1 ) => { ... };
    ( @is_one _ ) => { ... };
    ( @is_one 0 ) => { ... };
    ( @is_one 1 ) => { ... };
    ( $($part:tt)+ ) => { ... };
}

Builds a closure for bit-level matching of a value.

Syntax

The bitpat! macro takes a list of 1, 0 or _ tokens, each of which correspond to a bit in the values it will match against. A 1 token matches 1 bits, a 0 token matches 0 bits, and a _ token matches either one.

bitpat! expands to a closure that takes a value that is then matched against the specified pattern. The closure always returns a bool indicating whether the value matched, but its argument can be inferred to be any integer type.

If a bitpat! is matched against a value that consists of more bits than were specified in the pattern, the pattern is applied to the least significant bits in the value and other bits are ignored. In other words, the pattern is padded with _ symbols.

Likewise, if the pattern is applied to a value with fewer bits than in the pattern, the pattern will be truncated to match against the value. But do note that type inference might infer a larger integer type than you expect, so what seem to be excess bits in the pattern might get matched normally.

Example

Basic usage:

#[macro_use] extern crate bitpat;

// `0` patterns must always be 0, while `_` patterns don't matter.
assert!( bitpat!(0 0 0 0 _ _ _ _)(0b00000000u8));
assert!( bitpat!(0 0 0 0 _ _ _ _)(0b00001111u8));
assert!( bitpat!(0 0 0 0 _ _ _ _)(0b00001000u8));
assert!( bitpat!(0 0 0 0 _ _ _ _)(0b00000001u8));

assert!(!bitpat!(0 0 0 0 _ _ _ _)(0b10000000u8));
assert!(!bitpat!(0 0 0 0 _ _ _ _)(0b11110000u8));
assert!(!bitpat!(0 0 0 0 _ _ _ _)(0b11111111u8));
assert!(!bitpat!(0 0 0 0 _ _ _ _)(0b00011111u8));

// `1` patterns work analogously
assert!( bitpat!(1 1 1 _ _ 0 0 0)(0b11100000u8));
assert!( bitpat!(1 1 1 _ _ 0 0 0)(0b11110000u8));
assert!( bitpat!(1 1 1 _ _ 0 0 0)(0b11111000u8));
assert!( bitpat!(1 1 1 _ _ 0 0 0)(0b11101000u8));

assert!(!bitpat!(1 1 1 _ _ 0 0 0)(0b00000000u8));
assert!(!bitpat!(1 1 1 _ _ 0 0 0)(0b11111111u8));
assert!(!bitpat!(1 1 1 _ _ 0 0 0)(0b11111100u8));
assert!(!bitpat!(1 1 1 _ _ 0 0 0)(0b00001111u8));
assert!(!bitpat!(1 1 1 _ _ 0 0 0)(0b11000000u8));