Skip to content

Commit

Permalink
docs: Example for external flags
Browse files Browse the repository at this point in the history
  • Loading branch information
GrayJack committed Feb 19, 2025
1 parent f566240 commit 777caf6
Show file tree
Hide file tree
Showing 3 changed files with 39 additions and 6 deletions.
2 changes: 1 addition & 1 deletion bitflags-attr-macros/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,7 @@ mod typed;
///
/// ## Externally defined flags
///
/// If you're generating flags types for an external source, such as a C API, you can use the
/// If you're generating flags types from an external source, such as a C API, you can use the
/// `#[non_exhaustive]` attribute to communicate to the bitflags macro that there may be more valid
/// flags then the known flags.
///
Expand Down
37 changes: 37 additions & 0 deletions examples/external_flags.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
//! An example of defining an external flags definition using the [`bitflag`] macro.
use bitflag_attr::bitflag;

// If you're generating flags types from an external source, such as a C API, you can use the
// `#[non_exhaustive]` attribute to communicate to the bitflags macro that there may be more valid
// flags then the known flags.
//
// Without extra configuration, it defaults to `!0` (all bits set) as a mask of all bits the
/// external source may ever set, i.e. all bits are considered as possible values. But a value can
/// be defined using the `#[extra_valid_bits = <value>]` helper attribute.
#[bitflag(u32)]
#[non_exhaustive]
#[extra_valid_bits = 0b001001111]
#[derive(Debug, Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Hash)]
pub enum SimpleFlag {
A = 1,
B = 1 << 1,
C = 1 << 2,
D = 1 << 3,
E = 1 << 4,
F = A | B,
}

fn main() {
// A flag with only named flags
let mut flag = SimpleFlag::A | SimpleFlag::B | SimpleFlag::C;

// We added a potential external value
flag.set(SimpleFlag::from_bits_retain(1 << 6));

println!("{:#?}", flag);

// We truncate the value, but all potential external value will remain
flag.truncate();

println!("{:#?}", flag);
}
6 changes: 1 addition & 5 deletions examples/iter.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
use bitflag_attr::bitflag;

#[bitflag(u32)]
#[non_exhaustive]
#[extra_valid_bits = 0b001001111]
#[derive(Debug, Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Hash)]
pub enum SimpleFlag {
Flag1 = 1 << 9,
Expand All @@ -12,9 +10,7 @@ pub enum SimpleFlag {
}

fn main() {
let mut flag = SimpleFlag::Flag1 | SimpleFlag::Flag2 | SimpleFlag::Flag3;

flag.set(SimpleFlag::from_bits_retain(1 << 5));
let flag = SimpleFlag::Flag1 | SimpleFlag::Flag2 | SimpleFlag::Flag3;

println!("{:#?}", flag);

Expand Down

0 comments on commit 777caf6

Please sign in to comment.