Expand description

Bitflags handling and storage.

This crate allows you to define flag values using an enum and derive BitFlags to add convenience methods.

This implementation was heavily inspired by enumflags2 and bitflags and customized for use in a sawp parser. Consider using those two open source projects before resorting to this one. One key feature is that we are automatically generating ffi accessors using the sawp-ffi crate.

This crate works as follows:

  • enum YourEnum with a numeric representation (e.g. #[repr(u8)]) is used to define bit fields.
  • deriving BitFlags on this enum will add convenience methods for bitwise operations and implement the Flag trait.
  • Flag values are transparently stored as Flags<YourEnum> so you can perform more operations on this type.


See example module for a generated example as well.

use sawp_flags::{BitFlags, Flags, Flag};

/// Example enum
#[derive(Debug, Clone, Copy, PartialEq, BitFlags)]
pub enum Test {
    A = 0b0001,
    B = 0b0010,
    C = 0b0100,
    D = 0b1000,
    /// Variants can be a bitmask of the other fields like so
    E = Test::A as u8 | Test::B as u8 | Test::C as u8 | Test::D as u8,

// `flags` will be of transparent type `Flags<Test>`
let flags : Flags<Test> = Test::A | Test::C;

// convert a number to flags using `from_bits()`
assert_eq!(flags, Flags::<Test>::from_bits(0b101));

// convert flags to a number using `bits()`
assert_eq!(0b101, flags.bits());

// perform bitwise operations
assert_eq!(Test::A | Test::B | Test::C, flags | Test::B);
assert_eq!(Test::A, flags & Test::A);
assert_eq!(Test::C, flags ^ Test::A);

// check which flags are set
assert!(!flags.contains(Test::A | Test::B));
assert!(flags.intersects(Test::A | Test::B));


Example enum deriving BitFlags


Storage type for handling flags


A trait implemented by all flag enums.

A primitive numeric type to be used for flag storage.

Derive Macros

The BitFlags derive macro will implement the Flags Trait on your enum and provide convenience methods for bit operations and type conversions.