### Automatic Bit Value Inference Source: https://context7.com/meithecatte/enumflags2/llms.txt Enumflags2 can automatically assign bit values to enum variants without explicit discriminants. These inferred values are powers of two, starting from 1. Use `BitFlags::::all()` to get a `BitFlags` instance with all possible flags set. ```rust use enumflags2::{bitflags, BitFlags}; #[bitflags] #[repr(u8)] #[derive(Copy, Clone, Debug, PartialEq)] enum AutoFlags { First, Second = 0b0010, Third, Fourth = 0b1000, } assert_eq!(AutoFlags::First as u8, 1); assert_eq!(AutoFlags::Third as u8, 4); let all = BitFlags::::all(); assert_eq!(all.bits(), 0b1111); ``` -------------------------------- ### Initialize Boundary Values with empty and all Source: https://context7.com/meithecatte/enumflags2/llms.txt Creates empty or fully-set BitFlags instances, with support for compile-time constants. ```rust use enumflags2::{bitflags, BitFlags}; #[bitflags] #[repr(u8)] #[derive(Copy, Clone, Debug, PartialEq)] enum Level { Low = 1 << 0, Medium = 1 << 1, High = 1 << 2, Critical = 1 << 3, } // Empty set let none = BitFlags::::empty(); assert!(none.is_empty()); assert_eq!(none.bits(), 0); assert_eq!(none.len(), 0); // All flags set let all = BitFlags::::all(); assert!(all.is_all()); assert_eq!(all.bits(), 0b1111); assert_eq!(all.len(), 4); // Const versions for compile-time use const EMPTY: BitFlags = BitFlags::EMPTY; const ALL: BitFlags = BitFlags::ALL; ``` -------------------------------- ### BitFlags::empty and BitFlags::all - Boundary Values Source: https://context7.com/meithecatte/enumflags2/llms.txt Creates empty or fully-set BitFlags instances. Also available as constants BitFlags::EMPTY and BitFlags::ALL for const contexts. ```APIDOC ## BitFlags::empty and BitFlags::all - Boundary Values ### Description Creates empty or fully-set `BitFlags` instances. Also available as constants `BitFlags::EMPTY` and `BitFlags::ALL` for const contexts. ### Method `BitFlags::empty`, `BitFlags::all`, `BitFlags::EMPTY`, `BitFlags::ALL` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```rust use enumflags2::{bitflags, BitFlags}; #[bitflags] #[repr(u8)] #[derive(Copy, Clone, Debug, PartialEq)] enum Level { Low = 1 << 0, Medium = 1 << 1, High = 1 << 2, Critical = 1 << 3, } // Empty set let none = BitFlags::::empty(); assert!(none.is_empty()); assert_eq!(none.bits(), 0); assert_eq!(none.len(), 0); // All flags set let all = BitFlags::::all(); assert!(all.is_all()); assert_eq!(all.bits(), 0b1111); assert_eq!(all.len(), 4); // Const versions for compile-time use const EMPTY: BitFlags = BitFlags::EMPTY; const ALL: BitFlags = BitFlags::ALL; ``` ### Response #### Success Response (200) N/A (These are constructor methods) #### Response Example N/A ``` -------------------------------- ### Create BitFlags with make_bitflags! Macro Source: https://context7.com/meithecatte/enumflags2/llms.txt The `make_bitflags!` macro offers a concise syntax for creating `BitFlags` instances, particularly useful in `const` contexts where operators are not permitted. It allows combining flags using the `|` operator within the macro. ```rust use enumflags2::{bitflags, make_bitflags, BitFlags}; #[bitflags] #[repr(u8)] #[derive(Copy, Clone, Debug, PartialEq)] enum Status { Active = 1 << 0, Verified = 1 << 1, Premium = 1 << 2, Admin = 1 << 3, } // Create flag combinations with make_bitflags! let user_flags = make_bitflags!(Status::{Active | Verified}); assert_eq!(user_flags, Status::Active | Status::Verified); // Works in const contexts const ADMIN_FLAGS: BitFlags = make_bitflags!(Status::{Active | Verified | Admin}); const SINGLE_FLAG: BitFlags = make_bitflags!(Status::Premium); assert!(ADMIN_FLAGS.contains(Status::Admin)); assert_eq!(SINGLE_FLAG, Status::Premium); ``` -------------------------------- ### Bitwise Operators Source: https://context7.com/meithecatte/enumflags2/llms.txt Support for standard bitwise operators including union, intersection, symmetric difference, and complement. ```APIDOC ## Bitwise Operators ### Description Full support for `|`, `&`, `^`, `!` operators and their assignment variants for combining and manipulating flag sets. ``` -------------------------------- ### Debug and Display Formatting for BitFlags Source: https://context7.com/meithecatte/enumflags2/llms.txt BitFlags provides flexible formatting options. `Debug` shows the type name, numeric value, and flag names. `Display` shows only flag names. Numeric formats like `{:b}` and `{:x}` operate on the underlying bits. ```rust use enumflags2::{bitflags, BitFlags}; #[bitflags] #[repr(u8)] #[derive(Copy, Clone, Debug, PartialEq)] enum Color { Red = 1 << 0, Green = 1 << 1, Blue = 1 << 2, } let flags = Color::Red | Color::Blue; // Debug format: shows type name, bits, and flags assert_eq!(format!("{:?}", flags), "BitFlags(0b101, Red | Blue)"); // Display format: shows just the flags assert_eq!(format!("{}", flags), "Red | Blue"); // Binary format assert_eq!(format!("{:b}", flags), "101"); assert_eq!(format!("{:08b}", flags), "00000101"); // Hex format assert_eq!(format!("{:x}", flags), "5"); assert_eq!(format!("{:#04x}", flags), "0x05"); // Empty flags let empty = BitFlags::::empty(); assert_eq!(format!("{}", empty), ""); ``` -------------------------------- ### Serde Serialization and Deserialization for BitFlags Source: https://context7.com/meithecatte/enumflags2/llms.txt With the `serde` feature enabled, `BitFlags` can be serialized to and deserialized from its underlying numeric type. This allows `BitFlags` to be seamlessly integrated into JSON or other Serde-compatible formats. ```rust use enumflags2::{bitflags, BitFlags}; use serde::{Serialize, Deserialize}; #[bitflags] #[repr(u8)] #[derive(Copy, Clone, Debug, PartialEq, Serialize, Deserialize)] enum Permission { Read = 0b0001, Write = 0b0010, Execute = 0b0100, } #[derive(Serialize, Deserialize, Debug, PartialEq)] struct User { name: String, permissions: BitFlags, } fn main() -> Result<(), Box> { let user = User { name: "alice".to_string(), permissions: Permission::Read | Permission::Execute, }; // Serialize to JSON (permissions become numeric) let json = serde_json::to_string(&user)?; assert_eq!(json, r#"{"name":"alice","permissions":5}"#); // Deserialize back let restored: User = serde_json::from_str(&json)?; assert_eq!(restored, user); // Invalid bits cause deserialization error let invalid_json = r#"{"name":"bob","permissions":255}"#; let result: Result = serde_json::from_str(invalid_json); assert!(result.is_err()); Ok(()) } ``` -------------------------------- ### Combining and Comparing Flags with Bitwise Operators Source: https://context7.com/meithecatte/enumflags2/llms.txt The crate supports standard bitwise operators like |, &, ^, and ! for manipulating flag sets. ```rust use enumflags2::{bitflags, BitFlags}; #[bitflags] #[repr(u8)] #[derive(Copy, Clone, Debug, PartialEq)] enum Mode { A = 0b0001, B = 0b0010, C = 0b0100, D = 0b1000, } let set1 = Mode::A | Mode::B; // 0b0011 let set2 = Mode::B | Mode::C; // 0b0110 // Union (OR): flags in either set let union = set1 | set2; // 0b0111 = A | B | C assert_eq!(union, Mode::A | Mode::B | Mode::C); // Intersection (AND): flags in both sets let intersection = set1 & set2; // 0b0010 = B assert_eq!(intersection, Mode::B); // Symmetric difference (XOR): flags in one but not both let xor = set1 ^ set2; // 0b0101 = A | C assert_eq!(xor, Mode::A | Mode::C); // Complement (NOT): all flags except those set let complement = !set1; // 0b1100 = C | D assert_eq!(complement, Mode::C | Mode::D); // Assignment operators let mut flags = Mode::A.into(); flags |= Mode::B; // Add B flags &= Mode::A | Mode::B; // Keep only A and B flags ^= Mode::A; // Toggle A assert_eq!(flags, Mode::B); ``` -------------------------------- ### insert, remove, and toggle - Mutation Operations Source: https://context7.com/meithecatte/enumflags2/llms.txt Methods for modifying a BitFlags value in place by adding, removing, or toggling specific flags. ```APIDOC ## insert, remove, and toggle - Mutation Operations ### Description Methods for modifying a `BitFlags` value in place by adding, removing, or toggling specific flags. ### Method `insert`, `remove`, `toggle` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```rust use enumflags2::{bitflags, BitFlags}; #[bitflags] #[repr(u8)] #[derive(Copy, Clone, Debug, PartialEq)] enum State { Running = 0b0001, Paused = 0b0010, Error = 0b0100, Complete = 0b1000, } let mut state = State::Running.into(); // insert: Add flags state.insert(State::Paused); assert_eq!(state, State::Running | State::Paused); // remove: Remove flags state.remove(State::Running); assert_eq!(state, State::Paused); // toggle: Flip flags state.toggle(State::Paused | State::Error); assert_eq!(state, State::Error); // Paused removed, Error added // toggle again state.toggle(State::Error | State::Complete); assert_eq!(state, State::Complete); // Error removed, Complete added ``` ### Response #### Success Response (200) N/A (These methods modify the `BitFlags` in place and return `()`) #### Response Example N/A ``` -------------------------------- ### BitFlags::from_bits_truncate - Lossy Conversion Source: https://context7.com/meithecatte/enumflags2/llms.txt Creates a BitFlags from raw bits, silently ignoring any invalid bits. Useful when you want to accept partial data without errors. ```APIDOC ## BitFlags::from_bits_truncate - Lossy Conversion ### Description Creates a `BitFlags` from raw bits, silently ignoring any invalid bits. Useful when you want to accept partial data without errors. ### Method `BitFlags::from_bits_truncate` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```rust use enumflags2::{bitflags, BitFlags}; #[bitflags] #[repr(u8)] #[derive(Copy, Clone, Debug, PartialEq)] enum NetworkFlag { Connected = 0b0001, Secure = 0b0010, FastMode = 0b0100, } // Extra bits (0b11000) are silently ignored let flags = BitFlags::::from_bits_truncate(0b11011); assert_eq!(flags, NetworkFlag::Connected | NetworkFlag::Secure); assert_eq!(flags.bits(), 0b0011); // Completely invalid value becomes empty let empty = BitFlags::::from_bits_truncate(0b11110000); assert!(empty.is_empty()); ``` ### Response #### Success Response (200) N/A (This is a constructor method) #### Response Example N/A ``` -------------------------------- ### Introspecting Bits and Length Source: https://context7.com/meithecatte/enumflags2/llms.txt Use bits() to access the underlying integer representation and len() to count the number of set flags. ```rust use enumflags2::{bitflags, BitFlags}; #[bitflags] #[repr(u16)] #[derive(Copy, Clone, Debug, PartialEq)] enum Capability { FileRead = 1 << 0, FileWrite = 1 << 1, NetConnect = 1 << 2, NetListen = 1 << 3, ProcessSpawn = 1 << 4, } let caps = Capability::FileRead | Capability::FileWrite | Capability::NetConnect; // Get raw bits assert_eq!(caps.bits(), 0b00111); // Count set flags assert_eq!(caps.len(), 3); // Empty and all counts assert_eq!(BitFlags::::empty().len(), 0); assert_eq!(BitFlags::::all().len(), 5); // Use bits for storage/transmission fn serialize_capabilities(caps: BitFlags) -> u16 { caps.bits() } fn deserialize_capabilities(bits: u16) -> Result, &'static str> { BitFlags::from_bits(bits).map_err(|_| "invalid capability bits") } ``` -------------------------------- ### Const-Compatible APIs for BitFlags Source: https://context7.com/meithecatte/enumflags2/llms.txt Utilize `_c` suffixed functions for operations on BitFlags within const contexts, as trait-based operators are not supported. These require a `ConstToken` obtained from `BitFlags::CONST_TOKEN`. ```rust use enumflags2::{bitflags, BitFlags, make_bitflags}; #[bitflags] #[repr(u8)] #[derive(Copy, Clone, Debug, PartialEq)] enum Flag { A = 1 << 0, B = 1 << 1, C = 1 << 2, D = 1 << 3, } // All const operations const FLAGS_AB: BitFlags = make_bitflags!(Flag::{A | B}); const FLAGS_BC: BitFlags = make_bitflags!(Flag::{B | C}); // union_c: const bitwise OR const UNION: BitFlags = FLAGS_AB.union_c(FLAGS_BC); // A | B | C // intersection_c: const bitwise AND const INTERSECTION: BitFlags = FLAGS_AB.intersection_c(FLAGS_BC); // B // not_c: const complement (requires CONST_TOKEN) const COMPLEMENT: BitFlags = FLAGS_AB.not_c(BitFlags::CONST_TOKEN); // C | D // from_bits_truncate_c: const truncating conversion const FROM_BITS: BitFlags = BitFlags::from_bits_truncate_c(0xFF, BitFlags::CONST_TOKEN); // bits_c: const bits extraction const BITS: u8 = FLAGS_AB.bits_c(); fn main() { assert_eq!(UNION, Flag::A | Flag::B | Flag::C); assert_eq!(INTERSECTION, Flag::B); assert_eq!(COMPLEMENT, Flag::C | Flag::D); assert_eq!(FROM_BITS, BitFlags::::all()); assert_eq!(BITS, 0b0011); } ``` -------------------------------- ### bits and len - Introspection Source: https://context7.com/meithecatte/enumflags2/llms.txt Methods for retrieving the underlying integer representation and the count of set flags. ```APIDOC ## bits ### Description Returns the underlying integer representation of the bitflags. ## len ### Description Returns the count of set flags. ``` -------------------------------- ### BitFlags::from_bits - Safe Conversion from Raw Bits Source: https://context7.com/meithecatte/enumflags2/llms.txt Safely create a `BitFlags` instance from a raw integer value using `BitFlags::from_bits`. This method returns a `Result`, yielding an error if any invalid bits are present in the input integer. The error provides the invalid bits and a truncated `BitFlags` instance. ```rust use enumflags2::{bitflags, BitFlags}; #[bitflags] #[repr(u8)] #[derive(Copy, Clone, Debug, PartialEq)] enum Feature { Compression = 0b0001, Encryption = 0b0010, Caching = 0b0100, } // Valid bits - success let features = BitFlags::::from_bits(0b0011).unwrap(); assert!(features.contains(Feature::Compression)); assert!(features.contains(Feature::Encryption)); // Invalid bits - returns error let result = BitFlags::::from_bits(0b1000); // bit 3 is invalid assert!(result.is_err()); let error = result.unwrap_err(); assert_eq!(error.invalid_bits(), 0b1000); assert_eq!(error.truncate(), BitFlags::::empty()); ``` -------------------------------- ### Perform Lossy Conversion with from_bits_truncate Source: https://context7.com/meithecatte/enumflags2/llms.txt Creates a BitFlags instance from raw bits, silently ignoring any bits not defined in the enum. ```rust use enumflags2::{bitflags, BitFlags}; #[bitflags] #[repr(u8)] #[derive(Copy, Clone, Debug, PartialEq)] enum NetworkFlag { Connected = 0b0001, Secure = 0b0010, FastMode = 0b0100, } // Extra bits (0b11000) are silently ignored let flags = BitFlags::::from_bits_truncate(0b11011); assert_eq!(flags, NetworkFlag::Connected | NetworkFlag::Secure); assert_eq!(flags.bits(), 0b0011); // Completely invalid value becomes empty let empty = BitFlags::::from_bits_truncate(0b11110000); assert!(empty.is_empty()); ``` -------------------------------- ### Query Membership with contains and intersects Source: https://context7.com/meithecatte/enumflags2/llms.txt Checks for flag presence using contains (all flags must match) or intersects (at least one flag must match). ```rust use enumflags2::{bitflags, BitFlags}; #[bitflags] #[repr(u8)] #[derive(Copy, Clone, Debug, PartialEq)] enum Access { Read = 0b0001, Write = 0b0010, Execute = 0b0100, Delete = 0b1000, } let user_access = Access::Read | Access::Write | Access::Execute; let required_read = Access::Read; let required_admin = Access::Read | Access::Write | Access::Delete; // contains: ALL specified flags must be present assert!(user_access.contains(Access::Read)); assert!(user_access.contains(Access::Read | Access::Write)); assert!(!user_access.contains(required_admin)); // missing Delete // intersects: AT LEAST ONE flag must be shared assert!(user_access.intersects(Access::Read)); assert!(user_access.intersects(Access::Read | Access::Delete)); // has Read assert!(!user_access.intersects(Access::Delete)); // no overlap // Works with single flags too assert!(user_access.contains(Access::Execute)); assert!(!user_access.intersects(Access::Delete)); ``` -------------------------------- ### iter - Iterating Over Set Flags Source: https://context7.com/meithecatte/enumflags2/llms.txt Returns an iterator that yields each individual flag that is set. The iterator implements ExactSizeIterator and FusedIterator. ```APIDOC ## iter ### Description Returns an iterator that yields each individual flag that is set. The iterator is `ExactSizeIterator` and `FusedIterator`. ### Request Example ```rust let workdays = make_bitflags!(Day::{Monday | Tuesday | Wednesday | Thursday | Friday}); let days: Vec = workdays.iter().collect(); ``` ``` -------------------------------- ### Iterating Over Set Flags Source: https://context7.com/meithecatte/enumflags2/llms.txt Use iter() to retrieve an iterator over individual set flags. The iterator implements ExactSizeIterator and FusedIterator. ```rust use enumflags2::{bitflags, BitFlags, make_bitflags}; #[bitflags] #[repr(u8)] #[derive(Copy, Clone, Debug, PartialEq)] enum Day { Monday = 1 << 0, Tuesday = 1 << 1, Wednesday = 1 << 2, Thursday = 1 << 3, Friday = 1 << 4, Saturday = 1 << 5, Sunday = 1 << 6, } let workdays = make_bitflags!(Day::{Monday | Tuesday | Wednesday | Thursday | Friday}); // Iterate over flags let days: Vec = workdays.iter().collect(); assert_eq!(days, vec![Day::Monday, Day::Tuesday, Day::Wednesday, Day::Thursday, Day::Friday]); // Use in for loops for day in workdays { println!("{:?}", day); } // ExactSizeIterator - know the count assert_eq!(workdays.iter().len(), 5); // Collect back into BitFlags let weekend = [Day::Saturday, Day::Sunday]; let weekend_flags: BitFlags = weekend.iter().copied().collect(); assert_eq!(weekend_flags, Day::Saturday | Day::Sunday); ``` -------------------------------- ### Customize Default Value for BitFlags Source: https://context7.com/meithecatte/enumflags2/llms.txt Customize the default value of BitFlags using the `default` parameter in the `#[bitflags]` macro. This sets the initial flags when `BitFlags::default()` is called. ```rust use enumflags2::{bitflags, BitFlags}; #[bitflags(default = Medium | Color)] #[repr(u8)] #[derive(Copy, Clone, Debug, PartialEq)] enum Setting { Low = 0b0001, Medium = 0b0010, High = 0b0100, Color = 0b1000, } // Default includes Medium and Color let default_settings = BitFlags::::default(); assert_eq!(default_settings, Setting::Medium | Setting::Color); assert!(default_settings.contains(Setting::Medium)); assert!(default_settings.contains(Setting::Color)); assert!(!default_settings.contains(Setting::High)); ``` -------------------------------- ### Define and Use Bitflags with Enumflags2 Source: https://github.com/meithecatte/enumflags2/blob/master/README.md Define an enum with the `#[bitflags]` attribute and use `BitFlags` to combine enum variants. The debug output shows both the numeric value and the flag names. This is useful for representing sets of options or states. ```rust use enumflags2::{bitflags, make_bitflags, BitFlags}; #[bitflags] #[repr(u8)] #[derive(Copy, Clone, Debug, PartialEq)] enum Test { A = 0b0001, B = 0b0010, C, // unspecified variants pick unused bits automatically D = 0b1000, } // Flags can be combined with |, this creates a BitFlags of your type: let a_b: BitFlags = Test::A | Test::B; let a_c = Test::A | Test::C; let b_c_d = make_bitflags!(Test::{B | C | D}); // The debug output lets you inspect both the numeric value and // the actual flags: assert_eq!(format!("{:?}", a_b), "BitFlags(0b11, A | B)"); // But if you'd rather see only one of those, that's available too: assert_eq!(format!("{}", a_b), "A | B"); assert_eq!(format!("{:04b}", a_b), "0011"); // Iterate over the flags like a normal set assert_eq!(a_b.iter().collect::>(), &[Test::A, Test::B]); // Query the contents with contains and intersects assert!(a_b.contains(Test::A)); assert!(b_c_d.contains(Test::B | Test::C)); assert!(!(b_c_d.contains(a_b))); assert!(a_b.intersects(a_c)); assert!(!(a_b.intersects(Test::C | Test::D))); ``` -------------------------------- ### Customize Default Bitflags Value Source: https://github.com/meithecatte/enumflags2/blob/master/README.md Customize the default value for `BitFlags` by providing a combination of flags in the `#[bitflags(default = ...)]` attribute. This is useful when an empty set is not the desired default state. ```rust #[bitflags(default = B | C)] #[repr(u8)] #[derive(Copy, Clone, Debug, PartialEq)] enum Test { A = 0b0001, B = 0b0010, C = 0b0100, D = 0b1000, } assert_eq!(BitFlags::default(), Test::B | Test::C); ``` -------------------------------- ### Extracting a Single Flag Source: https://context7.com/meithecatte/enumflags2/llms.txt Use exactly_one() to return Some(flag) if exactly one flag is set, or None otherwise. This is useful for converting BitFlags back to a single enum variant. ```rust use enumflags2::{bitflags, BitFlags}; #[bitflags] #[repr(u8)] #[derive(Copy, Clone, Debug, PartialEq)] enum Priority { Low = 1 << 0, Normal = 1 << 1, High = 1 << 2, Urgent = 1 << 3, } // Single flag - returns Some let single: BitFlags = Priority::High.into(); assert_eq!(single.exactly_one(), Some(Priority::High)); // Multiple flags - returns None let multiple = Priority::High | Priority::Urgent; assert_eq!(multiple.exactly_one(), None); // Empty - returns None let empty = BitFlags::::empty(); assert_eq!(empty.exactly_one(), None); // Practical use: match on single-flag values fn handle_priority(flags: BitFlags) { match flags.exactly_one() { Some(Priority::Urgent) => println!("Handle urgently!"), Some(priority) => println!("Single priority: {:?}", priority), None if flags.is_empty() => println!("No priority set"), None => println!("Multiple priorities: {}", flags), } } ``` -------------------------------- ### exactly_one - Extract Single Flag Source: https://context7.com/meithecatte/enumflags2/llms.txt Returns Some(flag) if exactly one flag is set, otherwise returns None. Useful for converting a BitFlags back to a single enum value. ```APIDOC ## exactly_one ### Description Returns `Some(flag)` if exactly one flag is set, otherwise returns `None`. Useful for converting a `BitFlags` back to a single enum value. ### Response - **Result** (Option) - Returns the flag if exactly one is set, otherwise None. ``` -------------------------------- ### Safe Integer Conversion with TryFrom Source: https://context7.com/meithecatte/enumflags2/llms.txt Use `BitFlags::::try_from(value)` for fallible conversion from raw integer types. This method returns an error if the integer contains bits not defined in the enum, preventing unexpected behavior. The error object provides details about the invalid bits and a truncated version with only valid bits. ```rust use enumflags2::{bitflags, BitFlags}; use std::convert::TryFrom; #[bitflags] #[repr(u8)] #[derive(Copy, Clone, Debug, PartialEq)] enum Protocol { Http = 0b0001, Https = 0b0010, Ws = 0b0100, Wss = 0b1000, } // Valid conversion let flags = BitFlags::::try_from(0b0011u8).unwrap(); assert_eq!(flags, Protocol::Http | Protocol::Https); // Invalid bits cause error let result = BitFlags::::try_from(0b10000u8); assert!(result.is_err()); // Error provides details if let Err(e) = result { println!("Invalid bits: {:#b}", e.invalid_bits()); println!("Valid portion: {:?}", e.truncate()); } ``` -------------------------------- ### Define Bitflags with #[bitflags] Source: https://context7.com/meithecatte/enumflags2/llms.txt Use the `#[bitflags]` attribute macro to transform an enum into a bitflag type. Ensure each variant has one bit set and use `#[repr(uN)]` for the underlying integer size. Single flags can be converted to `BitFlags` using `.into()`, and flags can be combined using the bitwise OR operator. ```rust use enumflags2::{bitflags, BitFlags}; #[bitflags] #[repr(u8)] #[derive(Copy, Clone, Debug, PartialEq, Eq)] enum Permission { Read = 0b0001, Write = 0b0010, Execute = 0b0100, Delete = 0b1000, } // Single flags automatically convert to BitFlags let read: BitFlags = Permission::Read.into(); assert!(read.contains(Permission::Read)); assert!(!read.contains(Permission::Write)); // Combine flags with bitwise OR let read_write: BitFlags = Permission::Read | Permission::Write; assert_eq!(read_write.bits(), 0b0011); assert!(read_write.contains(Permission::Read)); assert!(read_write.contains(Permission::Write)); ``` -------------------------------- ### Modify Flags Conditionally with set Source: https://context7.com/meithecatte/enumflags2/llms.txt Updates flags based on a boolean condition, useful for runtime configuration. ```rust use enumflags2::{bitflags, BitFlags}; #[bitflags] #[repr(u8)] #[derive(Copy, Clone, Debug, PartialEq)] enum Option { Verbose = 0b0001, Debug = 0b0010, Quiet = 0b0100, Color = 0b1000, } fn configure_options(verbose: bool, debug: bool, use_color: bool) -> BitFlags