Struct enumflags2::BitFlags

source ·
#[repr(transparent)]
pub struct BitFlags<T, N = <T as RawBitFlags>::Numeric> { /* private fields */ }
Expand description

Represents a set of flags of some type T. T must have the #[bitflags] attribute applied.

A BitFlags<T> is as large as the T itself, and stores one flag per bit.

Memory layout

BitFlags<T> is marked with the #[repr(transparent)] trait, meaning it can be safely transmuted into the corresponding numeric type.

Usually, the same can be achieved by using BitFlags::from_bits, BitFlags::from_bits_truncate or BitFlags::from_bits_unchecked, but transmuting might still be useful if, for example, you’re dealing with an entire array of BitFlags.

Transmuting from a numeric type into BitFlags may also be done, but care must be taken to make sure that each set bit in the value corresponds to an existing flag (cf. from_bits_unchecked).

For example:

#[bitflags]
#[repr(u8)] // <-- the repr determines the numeric type
#[derive(Copy, Clone)]
enum TransmuteMe {
    One = 1 << 0,
    Two = 1 << 1,
}

// NOTE: we use a small, self-contained function to handle the slice
// conversion to make sure the lifetimes are right.
fn transmute_slice<'a>(input: &'a [BitFlags<TransmuteMe>]) -> &'a [u8] {
    unsafe {
        slice::from_raw_parts(input.as_ptr() as *const u8, input.len())
    }
}

let many_flags = &[
    TransmuteMe::One.into(),
    TransmuteMe::One | TransmuteMe::Two,
];

let as_nums = transmute_slice(many_flags);
assert_eq!(as_nums, &[0b01, 0b11]);

Implementation notes

You might expect this struct to be defined as

struct BitFlags<T: BitFlag> {
    value: T::Numeric
}

Ideally, that would be the case. However, because const fns cannot have trait bounds in current Rust, this would prevent us from providing most const fn APIs. As a workaround, we define BitFlags with two type parameters, with a default for the second one:

struct BitFlags<T, N = <T as BitFlag>::Numeric> {
    value: N,
    marker: PhantomData<T>,
}

The types substituted for T and N must always match, creating a BitFlags value where that isn’t the case is only possible with incorrect unsafe code.

Implementations§

Returns a BitFlags<T> if the raw value provided does not contain any illegal flags.

Create a BitFlags<T> from an underlying bitwise value. If any invalid bits are set, ignore them.

Create a new BitFlags unsafely, without checking if the bits form a valid bit pattern for the type.

Consider using from_bits or from_bits_truncate instead.

Safety

All bits set in val must correspond to a value of the enum.

Turn a T into a BitFlags<T>. Also available as flag.into().

Create a BitFlags with no flags set (in other words, with a value of 0).

See also: BitFlag::empty, a convenience reexport; BitFlags::EMPTY, the same functionality available as a constant for const fn code.

#[bitflags]
#[repr(u8)]
#[derive(Clone, Copy, PartialEq, Eq)]
enum MyFlag {
    One = 1 << 0,
    Two = 1 << 1,
    Three = 1 << 2,
}

let empty: BitFlags<MyFlag> = BitFlags::empty();
assert!(empty.is_empty());
assert_eq!(empty.contains(MyFlag::One), false);
assert_eq!(empty.contains(MyFlag::Two), false);
assert_eq!(empty.contains(MyFlag::Three), false);

Create a BitFlags with all flags set.

See also: BitFlag::all, a convenience reexport; BitFlags::ALL, the same functionality available as a constant for const fn code.

#[bitflags]
#[repr(u8)]
#[derive(Clone, Copy, PartialEq, Eq)]
enum MyFlag {
    One = 1 << 0,
    Two = 1 << 1,
    Three = 1 << 2,
}

let empty: BitFlags<MyFlag> = BitFlags::all();
assert!(empty.is_all());
assert_eq!(empty.contains(MyFlag::One), true);
assert_eq!(empty.contains(MyFlag::Two), true);
assert_eq!(empty.contains(MyFlag::Three), true);

An empty BitFlags. Equivalent to empty(), but works in a const context.

A BitFlags with all flags set. Equivalent to all(), but works in a const context.

A ConstToken for this type of flag.

Returns true if all flags are set

Returns true if no flag is set

Returns the number of flags set.

If exactly one flag is set, the flag is returned. Otherwise, returns None.

See also Itertools::exactly_one.

Returns the underlying bitwise value.

#[bitflags]
#[repr(u8)]
#[derive(Clone, Copy)]
enum Flags {
    Foo = 1 << 0,
    Bar = 1 << 1,
}

let both_flags = Flags::Foo | Flags::Bar;
assert_eq!(both_flags.bits(), 0b11);

Returns true if at least one flag is shared.

Returns true if all flags are contained.

Toggles the matching bits

Inserts the flags into the BitFlag

Removes the matching flags

Returns an iterator that yields each set flag

Create a new BitFlags unsafely, without checking if the bits form a valid bit pattern for the type.

Const variant of from_bits_unchecked.

Consider using from_bits_truncate_c instead.

Safety

All bits set in val must correspond to a value of the enum.

Create a BitFlags<T> from an underlying bitwise value. If any invalid bits are set, ignore them.

#[bitflags]
#[repr(u8)]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum MyFlag {
    One = 1 << 0,
    Two = 1 << 1,
    Three = 1 << 2,
}

const FLAGS: BitFlags<MyFlag> =
    BitFlags::<MyFlag>::from_bits_truncate_c(0b10101010, BitFlags::CONST_TOKEN);
assert_eq!(FLAGS, MyFlag::Two);

Bitwise OR — return value contains flag if either argument does.

Also available as a | b, but operator overloads are not usable in const fns at the moment.

Bitwise AND — return value contains flag if both arguments do.

Also available as a & b, but operator overloads are not usable in const fns at the moment.

Bitwise NOT — return value contains flag if argument doesn’t.

Also available as !a, but operator overloads are not usable in const fns at the moment.

Moreover, due to const fn limitations, not_c needs a ConstToken as an argument.

#[bitflags]
#[repr(u8)]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum MyFlag {
    One = 1 << 0,
    Two = 1 << 1,
    Three = 1 << 2,
}

const FLAGS: BitFlags<MyFlag> = make_bitflags!(MyFlag::{One | Two});
const NEGATED: BitFlags<MyFlag> = FLAGS.not_c(BitFlags::CONST_TOKEN);
assert_eq!(NEGATED, MyFlag::Three);

Returns the underlying bitwise value.

const variant of bits.

Trait Implementations§

Formats the value using the given formatter.
The resulting type after applying the & operator.
Performs the & operation. Read more
Performs the &= operation. Read more
The resulting type after applying the | operator.
Performs the | operation. Read more
Performs the |= operation. Read more
The resulting type after applying the ^ operator.
Performs the ^ operation. Read more
Performs the ^= operation. Read more
Returns a copy of the value. Read more
Performs copy-assignment from source. Read more
Formats the value using the given formatter. Read more

The default value returned is one with all flags unset, i. e. empty, unless customized.

Returns the “default value” for a type. Read more
Formats the value using the given formatter. Read more
Extends a collection with the contents of an iterator. Read more
🔬This is a nightly-only experimental API. (extend_one)
Extends a collection with exactly one element.
🔬This is a nightly-only experimental API. (extend_one)
Reserves capacity in a collection for the given number of additional elements. Read more
Converts to this type from the input type.
Creates a value from an iterator. Read more
Feeds this value into the given Hasher. Read more
Feeds a slice of this type into the given Hasher. Read more
Which kind of iterator are we turning this into?
The type of the elements being iterated over.
Creates an iterator from a value. Read more
Formats the value using the given formatter.
The resulting type after applying the ! operator.
Performs the unary ! operation. Read more
Formats the value using the given formatter.
This method tests for self and other values to be equal, and is used by ==. Read more
This method tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason. Read more
This method tests for self and other values to be equal, and is used by ==. Read more
This method tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason. Read more
The type returned in the event of a conversion error.
Performs the conversion.
The type returned in the event of a conversion error.
Performs the conversion.
The type returned in the event of a conversion error.
Performs the conversion.
The type returned in the event of a conversion error.
Performs the conversion.
The type returned in the event of a conversion error.
Performs the conversion.
Formats the value using the given formatter.

Auto Trait Implementations§

Blanket Implementations§

Gets the TypeId of self. Read more
Immutably borrows from an owned value. Read more
Mutably borrows from an owned value. Read more

Returns the argument unchanged.

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

The type returned in the event of a conversion error.
Performs the conversion.
The type returned in the event of a conversion error.
Performs the conversion.