bitflag_attr

Attribute Macro bitflag

Source
#[bitflag]
Expand description

An attribute macro that transforms an C-like enum into a bitflag struct implementing an type API similar to the bitflags crate, and implementing traits as listed below.

§Generated trait implementations

This macro generates some trait implementations: fmt::Debug, ops:Not, ops:BitAnd, ops:BitOr, ops:BitXor, ops:BitAndAssign, ops:BitOrAssign, ops:BitXorAssign, fmt::Binary, fmt::LowerHex, fmt::UpperHex, fmt::Octal, From, [Clone], [Copy], [Extend], [FromIterator], [IntoIterator]

If the macro receives no_auto_debug, the trait fmt::Debug will not be generated. Use this flag when you want to implement fmt::Debug manually or use the standard derive.

§Serde feature

If the crate is compiled with the serde feature, this crate will generate implementations for the serde::{Serialize, Deserialize} traits, but it will not import/re-export these traits, your project must have serde as dependency.

Having this feature enabled will also generate a type to represent the parsing error and helper functions to do parsing the generated type from strings. And will generate the implementation for the FromStr trait.

§Custom types

If the crate is compiled with the custom-types feature, it allows to use more than the types defined in Rust core (“i8”,u8,i16,u16,i32,u32,i64,u64,i128,u128,isize, usize,c_char,c_schar,c_uchar,c_short,c_ushort,c_int,c_uint,c_long,c_ulong, c_longlong,c_ulonglong) as long as it is a type alias to one of those types.

The reason it is behind a feature flag is that to ensure the validity of such constrain, we have to pay the price of having much worse error messages. With this feature enabled, a invalid type will cause a massive wall of error message.

§Example

use bitflag_attr::bitflag;

#[bitflag(u32)]
#[derive(PartialEq, PartialOrd, Eq, Ord, Hash)]
pub enum Flags {
    /// The value `A`, at bit position `0`.
    A = 0b00000001,
    /// The value `B`, at bit position `1`.
    B = 0b00000010,
    /// The value `C`, at bit position `2`.
    C = 0b00000100,

    /// The combination of `A`, `B`, and `C`.
    ABC = A | B | C,
}

Without generating fmt::Debug:

use bitflag_attr::bitflag;

#[bitflag(u32, no_auto_debug)]
#[derive(PartialEq, PartialOrd, Eq, Ord, Hash)]
pub enum Flags {
    /// The value `A`, at bit position `0`.
    A = 0b00000001,
    /// The value `B`, at bit position `1`.
    B = 0b00000010,
    /// The value `C`, at bit position `2`.
    C = 0b00000100,

    /// The combination of `A`, `B`, and `C`.
    ABC = A | B | C,
}

§Syntax

#[bitflag($ty[, no_auto_debug])]
$visibility enum $StructName {
    FlagOne = flag1_value_expr,
    FlagTwo = flag2_value_expr,
    // ...
    FlagN = flagn_value_expr,
}