Struct landlock::BitFlags

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.

§Comparison operators, PartialOrd and Ord

To make it possible to use BitFlags as the key of a [BTreeMap][std::collections::BTreeMap], BitFlags implements Ord. There is no meaningful total order for bitflags, so the implementation simply compares the integer values of the bits.

Unfortunately, this means that comparing BitFlags with an operator like <= will compile, and return values that are probably useless and not what you expect. In particular, <= does not check whether one value is a subset of the other. Use BitFlags::contains for that.

§Customizing Default

By default, creating an instance of BitFlags<T> with Default will result in an empty set. If that’s undesirable, you may customize this:

#[bitflags(default = B | C)]
#[repr(u8)]
#[derive(Copy, Clone, Debug, PartialEq)]
enum MyFlag {
    A = 0b0001,
    B = 0b0010,
    C = 0b0100,
    D = 0b1000,
}

assert_eq!(BitFlags::default(), MyFlag::B | MyFlag::C);

§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::bits in one direction, and BitFlags::from_bits, BitFlags::from_bits_truncate, or BitFlags::from_bits_unchecked in the other direction. However, transmuting might still be useful if, for example, you’re dealing with an entire array of BitFlags.

When transmuting into a BitFlags, make sure that each set bit 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>,
}

Manually providing a type for the N type parameter shouldn’t ever be necessary.

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§

§

impl<T> BitFlags<T>
where T: BitFlag,

pub fn iter(self) -> Iter<T>

Iterate over the BitFlags.

let flags = make_bitflags!(MyFlag::{A | C});

flags.iter()
    .for_each(|flag| println!("{:?}", flag));
§

impl<T> BitFlags<T>
where T: BitFlag,

pub const EMPTY: BitFlags<T> = _

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

pub const ALL: BitFlags<T> = _

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

pub const CONST_TOKEN: ConstToken<T, <T as RawBitFlags>::Numeric> = _

A [ConstToken] for this type of flag.

§

impl<T> BitFlags<T, u8>

pub const unsafe fn from_bits_unchecked_c( val: u8, const_token: ConstToken<T, u8>, ) -> BitFlags<T, u8>

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.

pub const fn from_bits_truncate_c( bits: u8, const_token: ConstToken<T, u8>, ) -> BitFlags<T, u8>

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);

pub const fn union_c(self, other: BitFlags<T, u8>) -> BitFlags<T, u8>

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.

pub const fn intersection_c(self, other: BitFlags<T, u8>) -> BitFlags<T, u8>

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.

pub const fn not_c(self, const_token: ConstToken<T, u8>) -> BitFlags<T, u8>

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);

pub const fn bits_c(self) -> u8

Returns the underlying bitwise value.

const variant of bits.

§

impl<T> BitFlags<T>
where T: BitFlag,

pub fn from_bits( bits: <T as RawBitFlags>::Numeric, ) -> Result<BitFlags<T>, FromBitsError<T>>

Create a BitFlags if the raw value provided does not contain any illegal flags.

See also: [a convenience re-export in the BitFlag trait][BitFlag::from_bits], which can help avoid the need for type hints.

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

let flags: BitFlags<MyFlag> = BitFlags::from_bits(0b11).unwrap();
assert_eq!(flags.contains(MyFlag::One), true);
assert_eq!(flags.contains(MyFlag::Two), true);
assert_eq!(flags.contains(MyFlag::Three), false);
let invalid = BitFlags::<MyFlag>::from_bits(1 << 3);
assert!(invalid.is_err());

pub fn from_bits_truncate(bits: <T as RawBitFlags>::Numeric) -> BitFlags<T>

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

See also: [a convenience re-export in the BitFlag trait][BitFlag::from_bits_truncate], which can help avoid the need for type hints.

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

let flags: BitFlags<MyFlag> = BitFlags::from_bits_truncate(0b1_1011);
assert_eq!(flags.contains(MyFlag::One), true);
assert_eq!(flags.contains(MyFlag::Two), true);
assert_eq!(flags.contains(MyFlag::Three), false);

pub unsafe fn from_bits_unchecked( val: <T as RawBitFlags>::Numeric, ) -> BitFlags<T>

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.

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

let flags: BitFlags<MyFlag> = unsafe {
    BitFlags::from_bits_unchecked(0b011)
};

assert_eq!(flags.contains(MyFlag::One), true);
assert_eq!(flags.contains(MyFlag::Two), true);
assert_eq!(flags.contains(MyFlag::Three), false);

pub fn from_flag(flag: T) -> BitFlags<T>

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

pub fn empty() -> BitFlags<T>

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);

pub fn all() -> BitFlags<T>

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);

pub fn is_all(self) -> bool

Returns true if all flags are set

pub fn is_empty(self) -> bool

Returns true if no flag is set

pub fn len(self) -> usize

Returns the number of flags set.

pub fn exactly_one(self) -> Option<T>

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

See also Itertools::exactly_one.

pub fn bits(self) -> <T as RawBitFlags>::Numeric

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);

pub fn intersects<B>(self, other: B) -> bool
where B: Into<BitFlags<T>>,

Returns true if at least one flag is shared.

pub fn contains<B>(self, other: B) -> bool
where B: Into<BitFlags<T>>,

Returns true if all flags are contained.

pub fn toggle<B>(&mut self, other: B)
where B: Into<BitFlags<T>>,

Toggles the matching bits

pub fn insert<B>(&mut self, other: B)
where B: Into<BitFlags<T>>,

Inserts the flags into the BitFlag

pub fn remove<B>(&mut self, other: B)
where B: Into<BitFlags<T>>,

Removes the matching flags

pub fn set<B>(&mut self, other: B, cond: bool)
where B: Into<BitFlags<T>>,

Inserts if cond holds, else removes

#[bitflags]
#[derive(Clone, Copy, PartialEq, Debug)]
#[repr(u8)]
enum MyFlag {
    A = 1 << 0,
    B = 1 << 1,
    C = 1 << 2,
}

let mut state = MyFlag::A | MyFlag::C;
state.set(MyFlag::A | MyFlag::B, false);

// Because the condition was false, both
// `A` and `B` are removed from the set
assert_eq!(state, MyFlag::C);

Trait Implementations§

§

impl<T> Binary for BitFlags<T>
where T: BitFlag, <T as RawBitFlags>::Numeric: Binary,

§

fn fmt(&self, fmt: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more
§

impl<T, B> BitAnd<B> for BitFlags<T>
where T: BitFlag, B: Into<BitFlags<T>>,

§

type Output = BitFlags<T>

The resulting type after applying the & operator.
§

fn bitand(self, other: B) -> BitFlags<T>

Performs the & operation. Read more
§

impl<T, B> BitAndAssign<B> for BitFlags<T>
where T: BitFlag, B: Into<BitFlags<T>>,

§

fn bitand_assign(&mut self, other: B)

Performs the &= operation. Read more
§

impl<T, B> BitOr<B> for BitFlags<T>
where T: BitFlag, B: Into<BitFlags<T>>,

§

type Output = BitFlags<T>

The resulting type after applying the | operator.
§

fn bitor(self, other: B) -> BitFlags<T>

Performs the | operation. Read more
§

impl<T, B> BitOrAssign<B> for BitFlags<T>
where T: BitFlag, B: Into<BitFlags<T>>,

§

fn bitor_assign(&mut self, other: B)

Performs the |= operation. Read more
§

impl<T, B> BitXor<B> for BitFlags<T>
where T: BitFlag, B: Into<BitFlags<T>>,

§

type Output = BitFlags<T>

The resulting type after applying the ^ operator.
§

fn bitxor(self, other: B) -> BitFlags<T>

Performs the ^ operation. Read more
§

impl<T, B> BitXorAssign<B> for BitFlags<T>
where T: BitFlag, B: Into<BitFlags<T>>,

§

fn bitxor_assign(&mut self, other: B)

Performs the ^= operation. Read more
§

impl<T, N> Clone for BitFlags<T, N>
where T: Clone, N: Clone,

§

fn clone(&self) -> BitFlags<T, N>

Returns a copy of the value. Read more
1.0.0 · source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
§

impl<T> Debug for BitFlags<T>
where T: BitFlag + Debug,

§

fn fmt(&self, fmt: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more
§

impl<T> Default for BitFlags<T>
where T: BitFlag,

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

§

fn default() -> BitFlags<T>

Returns the “default value” for a type. Read more
§

impl<T> Display for BitFlags<T>
where T: BitFlag + Debug,

§

fn fmt(&self, fmt: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more
§

impl<T, B> Extend<B> for BitFlags<T>
where T: BitFlag, B: Into<BitFlags<T>>,

§

fn extend<I>(&mut self, it: I)
where I: IntoIterator<Item = B>,

Extends a collection with the contents of an iterator. Read more
source§

fn extend_one(&mut self, item: A)

🔬This is a nightly-only experimental API. (extend_one)
Extends a collection with exactly one element.
source§

fn extend_reserve(&mut self, additional: usize)

🔬This is a nightly-only experimental API. (extend_one)
Reserves capacity in a collection for the given number of additional elements. Read more
§

impl<T> From<T> for BitFlags<T>
where T: BitFlag,

§

fn from(t: T) -> BitFlags<T>

Converts to this type from the input type.
§

impl<T, B> FromIterator<B> for BitFlags<T>
where T: BitFlag, B: Into<BitFlags<T>>,

§

fn from_iter<I>(it: I) -> BitFlags<T>
where I: IntoIterator<Item = B>,

Creates a value from an iterator. Read more
§

impl<T, N> Hash for BitFlags<T, N>
where N: Hash,

§

fn hash<H>(&self, state: &mut H)
where H: Hasher,

Feeds this value into the given Hasher. Read more
1.3.0 · source§

fn hash_slice<H>(data: &[Self], state: &mut H)
where H: Hasher, Self: Sized,

Feeds a slice of this type into the given Hasher. Read more
§

impl<T> IntoIterator for BitFlags<T>
where T: BitFlag,

§

type IntoIter = Iter<T>

Which kind of iterator are we turning this into?
§

type Item = T

The type of the elements being iterated over.
§

fn into_iter(self) -> <BitFlags<T> as IntoIterator>::IntoIter

Creates an iterator from a value. Read more
§

impl<T> LowerHex for BitFlags<T>
where T: BitFlag, <T as RawBitFlags>::Numeric: LowerHex,

§

fn fmt(&self, fmt: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more
§

impl<T> Not for BitFlags<T>
where T: BitFlag,

§

type Output = BitFlags<T>

The resulting type after applying the ! operator.
§

fn not(self) -> BitFlags<T>

Performs the unary ! operation. Read more
§

impl<T> Octal for BitFlags<T>
where T: BitFlag, <T as RawBitFlags>::Numeric: Octal,

§

fn fmt(&self, fmt: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more
§

impl<T, N> Ord for BitFlags<T, N>
where N: Ord,

§

fn cmp(&self, other: &BitFlags<T, N>) -> Ordering

This method returns an Ordering between self and other. Read more
1.21.0 · source§

fn max(self, other: Self) -> Self
where Self: Sized,

Compares and returns the maximum of two values. Read more
1.21.0 · source§

fn min(self, other: Self) -> Self
where Self: Sized,

Compares and returns the minimum of two values. Read more
1.50.0 · source§

fn clamp(self, min: Self, max: Self) -> Self
where Self: Sized + PartialOrd,

Restrict a value to a certain interval. Read more
§

impl<T> PartialEq<T> for BitFlags<T>
where T: BitFlag,

§

fn eq(&self, other: &T) -> bool

This method tests for self and other values to be equal, and is used by ==.
1.0.0 · source§

fn ne(&self, other: &Rhs) -> bool

This method tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
§

impl<T, N> PartialEq for BitFlags<T, N>
where N: PartialEq,

§

fn eq(&self, other: &BitFlags<T, N>) -> bool

This method tests for self and other values to be equal, and is used by ==.
1.0.0 · source§

fn ne(&self, other: &Rhs) -> bool

This method tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
§

impl<T, N> PartialOrd for BitFlags<T, N>
where N: PartialOrd,

§

fn partial_cmp(&self, other: &BitFlags<T, N>) -> Option<Ordering>

This method returns an ordering between self and other values if one exists. Read more
1.0.0 · source§

fn lt(&self, other: &Rhs) -> bool

This method tests less than (for self and other) and is used by the < operator. Read more
1.0.0 · source§

fn le(&self, other: &Rhs) -> bool

This method tests less than or equal to (for self and other) and is used by the <= operator. Read more
1.0.0 · source§

fn gt(&self, other: &Rhs) -> bool

This method tests greater than (for self and other) and is used by the > operator. Read more
1.0.0 · source§

fn ge(&self, other: &Rhs) -> bool

This method tests greater than or equal to (for self and other) and is used by the >= operator. Read more
§

impl<T> TryFrom<u128> for BitFlags<T>
where T: BitFlag<Numeric = u128>,

§

type Error = FromBitsError<T>

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

fn try_from( bits: <T as RawBitFlags>::Numeric, ) -> Result<BitFlags<T>, <BitFlags<T> as TryFrom<u128>>::Error>

Performs the conversion.
§

impl<T> TryFrom<u16> for BitFlags<T>
where T: BitFlag<Numeric = u16>,

§

type Error = FromBitsError<T>

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

fn try_from( bits: <T as RawBitFlags>::Numeric, ) -> Result<BitFlags<T>, <BitFlags<T> as TryFrom<u16>>::Error>

Performs the conversion.
§

impl<T> TryFrom<u32> for BitFlags<T>
where T: BitFlag<Numeric = u32>,

§

type Error = FromBitsError<T>

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

fn try_from( bits: <T as RawBitFlags>::Numeric, ) -> Result<BitFlags<T>, <BitFlags<T> as TryFrom<u32>>::Error>

Performs the conversion.
§

impl<T> TryFrom<u64> for BitFlags<T>
where T: BitFlag<Numeric = u64>,

§

type Error = FromBitsError<T>

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

fn try_from( bits: <T as RawBitFlags>::Numeric, ) -> Result<BitFlags<T>, <BitFlags<T> as TryFrom<u64>>::Error>

Performs the conversion.
§

impl<T> TryFrom<u8> for BitFlags<T>
where T: BitFlag<Numeric = u8>,

§

type Error = FromBitsError<T>

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

fn try_from( bits: <T as RawBitFlags>::Numeric, ) -> Result<BitFlags<T>, <BitFlags<T> as TryFrom<u8>>::Error>

Performs the conversion.
§

impl<T> UpperHex for BitFlags<T>
where T: BitFlag, <T as RawBitFlags>::Numeric: UpperHex,

§

fn fmt(&self, fmt: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more
§

impl<T, N> Copy for BitFlags<T, N>
where T: Copy, N: Copy,

§

impl<T, N> Eq for BitFlags<T, N>
where N: Eq,

Auto Trait Implementations§

§

impl<T, N> Freeze for BitFlags<T, N>
where N: Freeze,

§

impl<T, N> RefUnwindSafe for BitFlags<T, N>

§

impl<T, N> Send for BitFlags<T, N>
where N: Send, T: Send,

§

impl<T, N> Sync for BitFlags<T, N>
where N: Sync, T: Sync,

§

impl<T, N> Unpin for BitFlags<T, N>
where N: Unpin, T: Unpin,

§

impl<T, N> UnwindSafe for BitFlags<T, N>
where N: UnwindSafe, T: UnwindSafe,

Blanket Implementations§

source§

impl<T> Any for T
where T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
source§

impl<T> Borrow<T> for T
where T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<T> CloneToUninit for T
where T: Copy,

source§

unsafe fn clone_to_uninit(&self, dst: *mut T)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dst. Read more
source§

impl<T> CloneToUninit for T
where T: Clone,

source§

default unsafe fn clone_to_uninit(&self, dst: *mut T)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dst. Read more
source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

source§

impl<T, U> Into<U> for T
where U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

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

source§

impl<T> ToOwned for T
where T: Clone,

§

type Owned = T

The resulting type after obtaining ownership.
source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
source§

impl<T> ToString for T
where T: Display + ?Sized,

source§

default fn to_string(&self) -> String

Converts the given value to a String. Read more
source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.