#flags #enums #bitflags

macro enum-flags

EnumFlags is a csharp like enum flags implementation

7 releases

new 0.4.0 Dec 22, 2024
0.3.0 Feb 25, 2022
0.1.8 Aug 8, 2021
0.1.6 Jul 31, 2021

#36 in #bitflags

Download history 19/week @ 2024-09-01 68/week @ 2024-09-08 28/week @ 2024-09-15 92/week @ 2024-09-22 29/week @ 2024-09-29 48/week @ 2024-10-06 66/week @ 2024-10-13 168/week @ 2024-10-20 303/week @ 2024-10-27 327/week @ 2024-11-03 302/week @ 2024-11-10 143/week @ 2024-11-17 257/week @ 2024-11-24 635/week @ 2024-12-01 160/week @ 2024-12-08 346/week @ 2024-12-15

1,410 downloads per month
Used in 2 crates (via kmip-protocol)

MIT license

21KB
368 lines

LICENSE Documentation Crates.io Version

EnumFlags

EnumFlags is a csharp like enum flags implementation.

The generated code is no_std compatible.

Example

Since use the feature arbitrary_enum_discriminant, nightly channel is required.

#![feature(arbitrary_enum_discriminant)]
use enum_flags::enum_flags;

#[repr(u8)]  // default: #[repr(usize)]
#[enum_flags]
#[derive(Copy, Clone, PartialEq)] // can be omitted
enum Flags{
    None = 0,
    A = 1,
    B, // 2
    C = 4
}
fn main() {
    let e1: Flags = Flags::A | Flags::C;
    let e2 = Flags::B | Flags::C;

    assert_eq!(e1 | e2, Flags::A | Flags::B | Flags::C); // union
    assert_eq!(e1 & e2, Flags::C); // intersection
    assert_eq!(e1 ^ e2, Flags::A | Flags::B); // toggle
    assert_eq!(e1 & (!Flags::C), Flags::A); // deletion
    assert_eq!(e1 - Flags::C, Flags::A); // deletion

    assert_eq!(format!("{:?}", e1).as_str(), "(Flags::A | Flags::C)");
    assert!(e1.has_a());
    assert!(!e1.has_b());
    assert!(e1.has_flag(Flags::C));
    assert!(e1.contains(Flags::C));
    assert_eq!(match Flags::A | Flags::C {
        Flags::None => "None",
        Flags::A => "A",
        Flags::B => "B",
        Flags::C => "C",
        Flags::__Composed__(v) if v == Flags::A | Flags::B => "A and B",
        Flags::__Composed__(v) if v == Flags::A | Flags::C => "A and C",
        _ => "Others"
    }, "A and C")
}

Breaking Changes

  • before version 0.18
    #[derive(Copy, EnumFlags, Clone, PartialEq)]
    enum Flags {
        None = 0,
        A = 1,
        B = 2,
        C = 4
    }
    
  • version 0.30 later
    #[enum_flags] 
    #[derive(Copy, Clone, PartialEq)]
    enum Flags {
        None = 0,
        A = 1,
        B = 2,
        C = 4
    }
    

Dependencies

~1.5MB
~37K SLoC