#bit-flags #bit #bitmask

no-std flags

A macro to generate structures which behave like bitflags

7 releases

Uses old Rust 2015

0.1.5 Dec 22, 2020
0.1.4 Feb 1, 2020
0.1.3 Dec 6, 2018
0.1.2 Oct 8, 2018
0.0.0 Apr 21, 2018

#185 in No standard library

Download history 25/week @ 2024-07-22 27/week @ 2024-07-29 27/week @ 2024-08-05 40/week @ 2024-08-12 70/week @ 2024-08-19 26/week @ 2024-08-26 29/week @ 2024-09-02 44/week @ 2024-09-09 41/week @ 2024-09-16 67/week @ 2024-09-23 17/week @ 2024-09-30 55/week @ 2024-10-07 43/week @ 2024-10-14 36/week @ 2024-10-21 13/week @ 2024-10-28 19/week @ 2024-11-04

119 downloads per month
Used in 10 crates (7 directly)

MIT/Apache

38KB
750 lines

A typesafe bitmask flag generator useful for sets of C-style bitmask flags. It can be used for creating typesafe wrappers around C APIs.

The bitflags! macro generates a struct that manages a set of flags. The flags should only be defined for integer types, otherwise unexpected type errors may occur at compile time.

Example

extern crate bitflags;

bitflags::bitflags! {
    struct Flags: u32 {
        const A = 0b00000001;
        const B = 0b00000010;
        const C = 0b00000100;
        const ABC = Self::A.bits | Self::B.bits | Self::C.bits;
    }
}

fn main() {
    let e1 = Flags::A | Flags::C;
    let e2 = Flags::B | Flags::C;
    assert_eq!((e1 | e2), Flags::ABC);   // union
    assert_eq!((e1 & e2), Flags::C);     // intersection
    assert_eq!((e1 - e2), Flags::A);     // set difference
    assert_eq!(!e2, Flags::A);           // set complement
}

See example_generated::Flags for documentation of code generated by the above bitflags! expansion.

The generated structs can also be extended with type and trait implementations:

extern crate bitflags;

use std::fmt;

bitflags::bitflags! {
    struct Flags: u32 {
        const A = 0b00000001;
        const B = 0b00000010;
    }
}

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::Display for Flags {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "hi!")
    }
}

fn main() {
    let mut flags = Flags::A | Flags::B;
    flags.clear();
    assert!(flags.is_empty());
    assert_eq!(format!("{}", flags), "hi!");
    assert_eq!(format!("{:?}", Flags::A | Flags::B), "A | B");
    assert_eq!(format!("{:?}", Flags::B), "B");
}

Visibility

The generated struct and its associated flag constants are not exported out of the current module by default. A definition can be exported out of the current module by adding pub before flags:

extern crate bitflags;

mod example {
    bitflags::bitflags! {
        pub struct Flags1: u32 {
            const A = 0b00000001;
        }
    }
    bitflags::bitflags! {
        struct Flags2: u32 {
            const B = 0b00000010;
        }
    }
}

fn main() {
    let flag1 = example::Flags1::A;
    let flag2 = example::Flags2::B; // error: const `B` is private
}

Attributes

Attributes can be attached to the generated struct by placing them before the flags keyword.

Trait implementations

The Copy, Clone, PartialEq, Eq, and Hash traits automatically derived for the struct using the derive attribute. Additional traits can be derived by providing an explicit derive attribute on flags.

The Extend and FromIterator traits are implemented for the struct, too: Extend adds the union of the instances of the struct iterated over, while FromIterator calculates the union.

The Binary, Debug, LowerExp, Octal and UpperExp trait is also implemented by displaying the bits value of the internal struct.

Operators

The following operator traits are implemented for the generated struct:

  • BitOr and BitOrAssign: union
  • BitAnd and BitAndAssign: intersection
  • BitXor and BitXorAssign: toggle
  • Sub and SubAssign: set difference
  • Not: set complement

Methods

The following methods are defined for the generated struct:

  • empty: an empty set of flags
  • all: the set of all flags
  • bits: the raw value of the flags currently stored
  • from_bits: convert from underlying bit representation, unless that representation contains bits that do not correspond to a flag
  • from_bits_truncate: convert from underlying bit representation, dropping any bits that do not correspond to flags
  • is_empty: true if no flags are currently stored
  • is_all: true if all flags are currently set
  • intersects: true if there are flags common to both self and other
  • contains: true all of the flags in other are contained within self
  • insert: inserts the specified flags in-place
  • remove: removes the specified flags in-place
  • toggle: the specified flags will be inserted if not present, and removed if they are.
  • set: inserts or removes the specified flags depending on the passed value

Default

The Default trait is not automatically implemented for the generated struct.

If your default value is equal to 0 (which is the same value as calling empty() on the generated struct), you can simply derive Default:

extern crate bitflags;

bitflags::bitflags! {
    // Results in default value with bits: 0
    #[derive(Default)]
    struct Flags: u32 {
        const A = 0b00000001;
        const B = 0b00000010;
        const C = 0b00000100;
    }
}

fn main() {
    let derived_default: Flags = Default::default();
    assert_eq!(derived_default.bits(), 0);
}

If your default value is not equal to 0 you need to implement Default yourself:

extern crate bitflags;

bitflags::bitflags! {
    struct Flags: u32 {
        const A = 0b00000001;
        const B = 0b00000010;
        const C = 0b00000100;
    }
}

// explicit `Default` implementation
impl Default for Flags {
    fn default() -> Flags {
        Flags::A | Flags::C
    }
}

fn main() {
    let implemented_default: Flags = Default::default();
    assert_eq!(implemented_default, (Flags::A | Flags::C));
}

No runtime deps

Features