Module std::bitflags[src]
The bitflags! macro generates a struct that holds a set of C-style
bitmask flags. It is useful for creating typesafe wrappers for C APIs.
The flags should only be defined for integer types, otherwise unexpected type errors may occur at compile time.
Example
bitflags!( flags Flags: u32 { static FlagA = 0x00000001, static FlagB = 0x00000010, static FlagC = 0x00000100, static FlagABC = FlagA.bits | FlagB.bits | FlagC.bits } ) fn main() { let e1 = FlagA | FlagC; let e2 = FlagB | FlagC; assert!((e1 | e2) == FlagABC); // union assert!((e1 & e2) == FlagC); // intersection assert!((e1 - e2) == FlagA); // set difference assert!(!e2 == FlagA); // set complement }bitflags!( flags Flags: u32 { static FlagA = 0x00000001, static FlagB = 0x00000010, static FlagC = 0x00000100, static FlagABC = FlagA.bits | FlagB.bits | FlagC.bits } ) fn main() { let e1 = FlagA | FlagC; let e2 = FlagB | FlagC; assert!((e1 | e2) == FlagABC); // union assert!((e1 & e2) == FlagC); // intersection assert!((e1 - e2) == FlagA); // set difference assert!(!e2 == FlagA); // set complement }
The generated structs can also be extended with type and trait implementations:
use std::fmt; bitflags!( flags Flags: u32 { static FlagA = 0x00000001, static FlagB = 0x00000010 } ) 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::Show for Flags { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "hi!") } } fn main() { let mut flags = FlagA | FlagB; flags.clear(); assert!(flags.is_empty()); assert_eq!(format!("{}", flags).as_slice(), "hi!"); }
Attributes
Attributes can be attached to the generated struct by placing them
before the flags keyword.
Derived traits
The PartialEq and Clone traits are automatically derived for the struct using
the deriving attribute. Additional traits can be derived by providing an
explicit deriving attribute on flags.
Operators
The following operator traits are implemented for the generated struct:
BitOr: unionBitAnd: intersectionSub: set differenceNot: set complement
Methods
The following methods are defined for the generated struct:
empty: an empty set of flagsall: the set of all flagsbits: the raw value of the flags currently storedis_empty:trueif no flags are currently storedis_all:trueif all flags are currently setintersects:trueif there are flags common to bothselfandothercontains:trueall of the flags inotherare contained withinselfinsert: inserts the specified flags in-placeremove: removes the specified flags in-place
Macros
| bitflags! |