Expand description
Generate types for C-style flags with ergonomic APIs.
§Getting started
Addbitflags
to yourCargo.toml
:
[dependencies.bitflags]version = "2.9.0"
§Generating flags types
Use thebitflags
macro to generate flags types:
usebitflags::bitflags;bitflags! {pub structFlags: u32 {constA =0b00000001;constB =0b00000010;constC =0b00000100; }}
See the docs for thebitflags
macro for the full syntax.
Also see theexample_generated
module for an example of what thebitflags
macro generates for a flags type.
§Externally defined flags
If you’re generating flags types for an external source, such as a C API, you can definean extra unnamed flag as a mask of all bits the external source may ever set. Usually this would be all bits (!0
):
bitflags! {pub structFlags: u32 {constA =0b00000001;constB =0b00000010;constC =0b00000100;// The source may set any bitsconst _= !0; }}
Why should you do this? Generated methods likeall
and truncating operators like!
only considerbits in defined flags. Adding an unnamed flag makes those methods consider additional bits,without generating additional constants for them. It helps compatibility when the external sourcemay start setting additional bits at any time. Theknown and unknown bitssection has more details on this behavior.
§Custom derives
You can derive some traits on generated flags types if you enable Cargo features. The followinglibraries are currently supported:
serde
: Support#[derive(Serialize, Deserialize)]
, using text for human-readable formats,and a raw number for binary formats.arbitrary
: Support#[derive(Arbitrary)]
, only generating flags values with known bits.bytemuck
: Support#[derive(Pod, Zeroable)]
, for casting between flags values and theirunderlying bits values.
You can also define your own flags type outside of thebitflags
macro and then use it to generate methods.This can be useful if you need a custom#[derive]
attribute for a library thatbitflags
doesn’tnatively support:
#[derive(SomeTrait)]pub structFlags(u32);bitflags! {implFlags: u32 {constA =0b00000001;constB =0b00000010;constC =0b00000100; }}
§Adding custom methods
Thebitflags
macro supports attributes on generated flags types within the macro itself, whileimpl
blocks can be added outside of it:
bitflags! {// Attributes can be applied to flags types#[repr(transparent)] #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]pub structFlags: u32 {constA =0b00000001;constB =0b00000010;constC =0b00000100; }}// Impl blocks can be added to flags typesimplFlags {pub fnas_u64(&self) -> u64 {self.bits()asu64 }}
§Working with flags values
Use generated constants and standard bitwise operators to interact with flags values:
// unionletab = Flags::A | Flags::B;// intersectionleta = ab & Flags::A;// differenceletb = ab - Flags::A;// complementletc = !ab;
See the docs for theFlags
trait for more details on operators and how they behave.
§Formatting and parsing
bitflags
defines a text format that can be used to convert any flags value to and from strings.
See theparser
module for more details.
§Specification
The terminology and behavior of generated flags types isspecified in the source repository.Details are repeated in these docs where appropriate, but is exhaustively listed in the spec. Somethings are worth calling out explicitly here.
§Flags types, flags values, flags
The spec and these docs use consistent terminology to refer to things in the bitflags domain:
- Bits type: A type that defines a fixed number of bits at specific locations.
- Flag: A set of bits in a bits type that may have a unique name.
- Flags type: A set of defined flags over a specific bits type.
- Flags value: An instance of a flags type using its specific bits value for storage.
bitflags! {structFlagsType: u8 {// -- Bits type// --------- Flags typeconstA =1;// ----- Flag}}letflag = FlagsType::A;// ---- Flags value
§Known and unknown bits
Any bits in a flag you define are calledknown bits. Any other bits areunknown bits.In the following flags type:
bitflags! {structFlags: u8 {constA =1;constB =1<<1;constC =1<<2; }}
The known bits are0b0000_0111
and the unknown bits are0b1111_1000
.
bitflags
doesn’t guarantee that a flags value will only ever have known bits set, but some operatorswill unset any unknown bits they encounter. In a future version ofbitflags
, all operators willunset unknown bits.
If you’re usingbitflags
for flags types defined externally, such as from C, you probably want allbits to be considered known, in case that external source changes. You can do this using an unnamedflag, as described inexternally defined flags.
§Zero-bit flags
Flags with no bits set should be avoided because they interact strangely withFlags::contains
andFlags::intersects
. A zero-bit flag is always contained, but is never intersected. Thenames of zero-bit flags can be parsed, but are never formatted.
§Multi-bit flags
Flags that set multiple bits should be avoided unless each bit is also in a single-bit flag.Take the following flags type as an example:
bitflags! {structFlags: u8 {constA =1;constB =1|1<<1; }}
The result ofFlags::A ^ Flags::B
is0b0000_0010
, which doesn’t correspond to eitherFlags::A
orFlags::B
even though it’s still a known bit.
Re-exports§
pub use traits::BitFlags;
Deprecated
Modules§
- example_
generated - This module shows an example of code generated by the macro.IT MUST NOT BE USED OUTSIDE THISCRATE.
- iter
- Yield the bits of a source flags value in a set of contained flags values.
- parser
- Parsing flags from text.
Macros§
- bitflags
- Generate a flags type.
- bitflags_
match - A macro that matches flags values, similar to Rust’s
match
statement.
Structs§
- Flag
- A defined flags value that may be named or unnamed.