enumflags2/lib.rs
1//! # Enum Flags
2//! `enumflags2` implements the classic bitflags datastructure. Annotate an enum
3//! with `#[bitflags]`, and `BitFlags<YourEnum>` will be able to hold arbitrary combinations
4//! of your enum within the space of a single integer.
5//!
6//! ## Example
7//! ```
8//! use enumflags2::{bitflags, make_bitflags, BitFlags};
9//!
10//! #[bitflags]
11//! #[repr(u8)]
12//! #[derive(Copy, Clone, Debug, PartialEq)]
13//! enum Test {
14//! A = 0b0001,
15//! B = 0b0010,
16//! C, // unspecified variants pick unused bits automatically
17//! D = 0b1000,
18//! }
19//!
20//! // Flags can be combined with |, this creates a BitFlags of your type:
21//! let a_b: BitFlags<Test> = Test::A | Test::B;
22//! let a_c = Test::A | Test::C;
23//! let b_c_d = make_bitflags!(Test::{B | C | D});
24//!
25//! // The debug output lets you inspect both the numeric value and
26//! // the actual flags:
27//! assert_eq!(format!("{:?}", a_b), "BitFlags<Test>(0b11, A | B)");
28//!
29//! // But if you'd rather see only one of those, that's available too:
30//! assert_eq!(format!("{}", a_b), "A | B");
31//! assert_eq!(format!("{:04b}", a_b), "0011");
32//!
33//! // Iterate over the flags like a normal set
34//! assert_eq!(a_b.iter().collect::<Vec<_>>(), &[Test::A, Test::B]);
35//!
36//! // Query the contents with contains and intersects
37//! assert!(a_b.contains(Test::A));
38//! assert!(b_c_d.contains(Test::B | Test::C));
39//! assert!(!(b_c_d.contains(a_b)));
40//!
41//! assert!(a_b.intersects(a_c));
42//! assert!(!(a_b.intersects(Test::C | Test::D)));
43//! ```
44//!
45//! ## Optional Feature Flags
46//!
47//! - [`serde`](https://serde.rs/) implements `Serialize` and `Deserialize`
48//! for `BitFlags<T>`.
49//! - `std` implements `std::error::Error` for `FromBitsError`.
50//!
51//! ## `const fn`-compatible APIs
52//!
53//! **Background:** The subset of `const fn` features currently stabilized is pretty limited.
54//! Most notably, [const traits are still at the RFC stage][const-trait-rfc],
55//! which makes it impossible to use any overloaded operators in a const
56//! context.
57//!
58//! **Naming convention:** If a separate, more limited function is provided
59//! for usage in a `const fn`, the name is suffixed with `_c`.
60//!
61//! **Blanket implementations:** If you attempt to write a `const fn` ranging
62//! over `T: BitFlag`, you will be met with an error explaining that currently,
63//! the only allowed trait bound for a `const fn` is `?Sized`. You will probably
64//! want to write a separate implementation for `BitFlags<T, u8>`,
65//! `BitFlags<T, u16>`, etc — probably generated by a macro.
66//! This strategy is often used by `enumflags2` itself; to avoid clutter, only
67//! one of the copies is shown in the documentation.
68//!
69//! ## Customizing `Default`
70//!
71//! By default, creating an instance of `BitFlags<T>` with `Default` will result in an empty
72//! set. If that's undesirable, you may customize this:
73//!
74//! ```
75//! # use enumflags2::{BitFlags, bitflags};
76//! #[bitflags(default = B | C)]
77//! #[repr(u8)]
78//! #[derive(Copy, Clone, Debug, PartialEq)]
79//! enum Test {
80//! A = 0b0001,
81//! B = 0b0010,
82//! C = 0b0100,
83//! D = 0b1000,
84//! }
85//!
86//! assert_eq!(BitFlags::default(), Test::B | Test::C);
87//! ```
88//!
89//! [const-trait-rfc]: https://github.com/rust-lang/rfcs/pull/2632
90#![warn(missing_docs)]
91#![cfg_attr(all(not(test), not(feature = "std")), no_std)]
92
93use core::iter::{FromIterator, FusedIterator};
94use core::marker::PhantomData;
95use core::{cmp, ops};
96
97#[allow(unused_imports)]
98#[macro_use]
99extern crate enumflags2_derive;
100
101#[doc(hidden)]
102pub use enumflags2_derive::bitflags_internal as bitflags;
103
104// Internal macro: expand into a separate copy for each supported numeric type.
105macro_rules! for_each_uint {
106 ( $d:tt $tyvar:ident $dd:tt $docattr:ident => $($input:tt)* ) => {
107 macro_rules! implement {
108 ( $d $tyvar:ty => $d($d $docattr:meta)? ) => {
109 $($input)*
110 }
111 }
112
113 implement! { u8 => }
114 implement! { u16 => doc(hidden) }
115 implement! { u32 => doc(hidden) }
116 implement! { u64 => doc(hidden) }
117 implement! { u128 => doc(hidden) }
118 }
119}
120
121/// A trait automatically implemented by `#[bitflags]` to make the enum
122/// a valid type parameter for `BitFlags<T>`.
123pub trait BitFlag: Copy + Clone + 'static + _internal::RawBitFlags {
124 /// Create a `BitFlags` with no flags set (in other words, with a value of 0).
125 ///
126 /// This is a convenience reexport of [`BitFlags::empty`]. It can be called with
127 /// `MyFlag::empty()`, thus bypassing the need for type hints in some situations.
128 ///
129 /// ```
130 /// # use enumflags2::{bitflags, BitFlags};
131 /// #[bitflags]
132 /// #[repr(u8)]
133 /// #[derive(Clone, Copy, PartialEq, Eq)]
134 /// enum MyFlag {
135 /// One = 1 << 0,
136 /// Two = 1 << 1,
137 /// Three = 1 << 2,
138 /// }
139 ///
140 /// use enumflags2::BitFlag;
141 ///
142 /// let empty = MyFlag::empty();
143 /// assert!(empty.is_empty());
144 /// assert_eq!(empty.contains(MyFlag::One), false);
145 /// assert_eq!(empty.contains(MyFlag::Two), false);
146 /// assert_eq!(empty.contains(MyFlag::Three), false);
147 /// ```
148 #[inline]
149 fn empty() -> BitFlags<Self> {
150 BitFlags::empty()
151 }
152
153 /// Create a `BitFlags` with all flags set.
154 ///
155 /// This is a convenience reexport of [`BitFlags::all`]. It can be called with
156 /// `MyFlag::all()`, thus bypassing the need for type hints in some situations.
157 ///
158 /// ```
159 /// # use enumflags2::{bitflags, BitFlags};
160 /// #[bitflags]
161 /// #[repr(u8)]
162 /// #[derive(Clone, Copy, PartialEq, Eq)]
163 /// enum MyFlag {
164 /// One = 1 << 0,
165 /// Two = 1 << 1,
166 /// Three = 1 << 2,
167 /// }
168 ///
169 /// use enumflags2::BitFlag;
170 ///
171 /// let empty = MyFlag::all();
172 /// assert!(empty.is_all());
173 /// assert_eq!(empty.contains(MyFlag::One), true);
174 /// assert_eq!(empty.contains(MyFlag::Two), true);
175 /// assert_eq!(empty.contains(MyFlag::Three), true);
176 /// ```
177 #[inline]
178 fn all() -> BitFlags<Self> {
179 BitFlags::all()
180 }
181}
182
183/// While the module is public, this is only the case because it needs to be
184/// accessed by the macro. Do not use this directly. Stability guarantees
185/// don't apply.
186#[doc(hidden)]
187pub mod _internal {
188 /// A trait automatically implemented by `#[bitflags]` to make the enum
189 /// a valid type parameter for `BitFlags<T>`.
190 ///
191 /// # Safety
192 ///
193 /// The values should reflect reality, like they do if the implementation
194 /// is generated by the procmacro.
195 pub unsafe trait RawBitFlags: Copy + Clone + 'static {
196 /// The underlying integer type.
197 type Numeric: BitFlagNum;
198
199 /// A value with no bits set.
200 const EMPTY: Self::Numeric;
201
202 /// The value used by the Default implementation. Equivalent to EMPTY, unless
203 /// customized.
204 const DEFAULT: Self::Numeric;
205
206 /// A value with all flag bits set.
207 const ALL_BITS: Self::Numeric;
208
209 /// The name of the type for debug formatting purposes.
210 ///
211 /// This is typically `BitFlags<EnumName>`
212 const BITFLAGS_TYPE_NAME: &'static str;
213
214 /// Return the bits as a number type.
215 fn bits(self) -> Self::Numeric;
216 }
217
218 use ::core::cmp::PartialOrd;
219 use ::core::fmt;
220 use ::core::ops::{BitAnd, BitOr, BitXor, Not, Sub};
221
222 pub trait BitFlagNum:
223 Default
224 + BitOr<Self, Output = Self>
225 + BitAnd<Self, Output = Self>
226 + BitXor<Self, Output = Self>
227 + Sub<Self, Output = Self>
228 + Not<Output = Self>
229 + PartialOrd<Self>
230 + fmt::Debug
231 + fmt::Binary
232 + Copy
233 + Clone
234 {
235 const ONE: Self;
236
237 fn is_power_of_two(self) -> bool;
238 fn count_ones(self) -> u32;
239 fn wrapping_neg(self) -> Self;
240 }
241
242 for_each_uint! { $ty $hide_docs =>
243 impl BitFlagNum for $ty {
244 const ONE: Self = 1;
245
246 fn is_power_of_two(self) -> bool {
247 <$ty>::is_power_of_two(self)
248 }
249
250 fn count_ones(self) -> u32 {
251 <$ty>::count_ones(self)
252 }
253
254 fn wrapping_neg(self) -> Self {
255 <$ty>::wrapping_neg(self)
256 }
257 }
258 }
259
260 // Re-export libcore so the macro doesn't inject "extern crate" downstream.
261 pub mod core {
262 pub use core::{convert, ops, option};
263 }
264
265 pub struct AssertionSucceeded;
266 pub struct AssertionFailed;
267 pub trait ExactlyOneBitSet {
268 type X;
269 }
270 impl ExactlyOneBitSet for AssertionSucceeded {
271 type X = ();
272 }
273
274 pub trait AssertionHelper {
275 type Status;
276 }
277
278 impl AssertionHelper for [(); 1] {
279 type Status = AssertionSucceeded;
280 }
281
282 impl AssertionHelper for [(); 0] {
283 type Status = AssertionFailed;
284 }
285
286 pub const fn next_bit(x: u128) -> u128 {
287 1 << x.trailing_ones()
288 }
289}
290
291use _internal::BitFlagNum;
292
293// Internal debug formatting implementations
294mod formatting;
295
296// impl TryFrom<T::Numeric> for BitFlags<T>
297mod fallible;
298pub use crate::fallible::FromBitsError;
299
300/// Represents a set of flags of some type `T`.
301/// `T` must have the `#[bitflags]` attribute applied.
302///
303/// A `BitFlags<T>` is as large as the `T` itself,
304/// and stores one flag per bit.
305///
306/// ## Memory layout
307///
308/// `BitFlags<T>` is marked with the `#[repr(transparent)]` trait, meaning
309/// it can be safely transmuted into the corresponding numeric type.
310///
311/// Usually, the same can be achieved by using [`BitFlags::from_bits`],
312/// [`BitFlags::from_bits_truncate`] or [`BitFlags::from_bits_unchecked`],
313/// but transmuting might still be useful if, for example, you're dealing with
314/// an entire array of `BitFlags`.
315///
316/// Transmuting from a numeric type into `BitFlags` may also be done, but
317/// care must be taken to make sure that each set bit in the value corresponds
318/// to an existing flag
319/// (cf. [`from_bits_unchecked`][BitFlags::from_bits_unchecked]).
320///
321/// For example:
322///
323/// ```
324/// # use enumflags2::{BitFlags, bitflags};
325/// #[bitflags]
326/// #[repr(u8)] // <-- the repr determines the numeric type
327/// #[derive(Copy, Clone)]
328/// enum TransmuteMe {
329/// One = 1 << 0,
330/// Two = 1 << 1,
331/// }
332///
333/// # use std::slice;
334/// // NOTE: we use a small, self-contained function to handle the slice
335/// // conversion to make sure the lifetimes are right.
336/// fn transmute_slice<'a>(input: &'a [BitFlags<TransmuteMe>]) -> &'a [u8] {
337/// unsafe {
338/// slice::from_raw_parts(input.as_ptr() as *const u8, input.len())
339/// }
340/// }
341///
342/// let many_flags = &[
343/// TransmuteMe::One.into(),
344/// TransmuteMe::One | TransmuteMe::Two,
345/// ];
346///
347/// let as_nums = transmute_slice(many_flags);
348/// assert_eq!(as_nums, &[0b01, 0b11]);
349/// ```
350///
351/// ## Implementation notes
352///
353/// You might expect this struct to be defined as
354///
355/// ```ignore
356/// struct BitFlags<T: BitFlag> {
357/// value: T::Numeric
358/// }
359/// ```
360///
361/// Ideally, that would be the case. However, because `const fn`s cannot
362/// have trait bounds in current Rust, this would prevent us from providing
363/// most `const fn` APIs. As a workaround, we define `BitFlags` with two
364/// type parameters, with a default for the second one:
365///
366/// ```ignore
367/// struct BitFlags<T, N = <T as BitFlag>::Numeric> {
368/// value: N,
369/// marker: PhantomData<T>,
370/// }
371/// ```
372///
373/// The types substituted for `T` and `N` must always match, creating a
374/// `BitFlags` value where that isn't the case is only possible with
375/// incorrect unsafe code.
376#[derive(Copy, Clone, Eq)]
377#[repr(transparent)]
378pub struct BitFlags<T, N = <T as _internal::RawBitFlags>::Numeric> {
379 val: N,
380 marker: PhantomData<T>,
381}
382
383/// `make_bitflags!` provides a succint syntax for creating instances of
384/// `BitFlags<T>`. Instead of repeating the name of your type for each flag
385/// you want to add, try `make_bitflags!(Flags::{Foo | Bar})`.
386/// ```
387/// use enumflags2::{bitflags, make_bitflags};
388/// #[bitflags]
389/// #[repr(u8)]
390/// #[derive(Clone, Copy, Debug)]
391/// enum Test {
392/// A = 1 << 0,
393/// B = 1 << 1,
394/// C = 1 << 2,
395/// }
396/// let x = make_bitflags!(Test::{A | C});
397/// assert_eq!(x, Test::A | Test::C);
398/// ```
399#[macro_export]
400macro_rules! make_bitflags {
401 ( $enum:ident ::{ $($variant:ident)|* } ) => {
402 {
403 let mut n = 0;
404 $(
405 {
406 let flag: $enum = $enum::$variant;
407 n |= flag as <$enum as $crate::_internal::RawBitFlags>::Numeric;
408 }
409 )*
410 // SAFETY: The value has been created from numeric values of the underlying
411 // enum, so only valid bits are set.
412 unsafe { $crate::BitFlags::<$enum>::from_bits_unchecked_c(
413 n, $crate::BitFlags::CONST_TOKEN) }
414 }
415 }
416}
417
418/// The default value returned is one with all flags unset, i. e. [`empty`][Self::empty],
419/// unless [customized](index.html#customizing-default).
420impl<T> Default for BitFlags<T>
421where
422 T: BitFlag,
423{
424 #[inline(always)]
425 fn default() -> Self {
426 BitFlags {
427 val: T::DEFAULT,
428 marker: PhantomData,
429 }
430 }
431}
432
433impl<T: BitFlag> From<T> for BitFlags<T> {
434 #[inline(always)]
435 fn from(t: T) -> BitFlags<T> {
436 Self::from_flag(t)
437 }
438}
439
440/// Workaround for `const fn` limitations.
441///
442/// Some `const fn`s in this crate will need an instance of this type
443/// for some type-level information usually provided by traits.
444/// For an example of usage, see [`not_c`][BitFlags::not_c].
445pub struct ConstToken<T, N>(BitFlags<T, N>);
446
447impl<T> BitFlags<T>
448where
449 T: BitFlag,
450{
451 /// Returns a `BitFlags<T>` if the raw value provided does not contain
452 /// any illegal flags.
453 #[inline]
454 pub fn from_bits(bits: T::Numeric) -> Result<Self, FromBitsError<T>> {
455 let flags = Self::from_bits_truncate(bits);
456 if flags.bits() == bits {
457 Ok(flags)
458 } else {
459 Err(FromBitsError {
460 flags,
461 invalid: bits & !flags.bits(),
462 })
463 }
464 }
465
466 /// Create a `BitFlags<T>` from an underlying bitwise value. If any
467 /// invalid bits are set, ignore them.
468 #[must_use]
469 #[inline(always)]
470 pub fn from_bits_truncate(bits: T::Numeric) -> Self {
471 // SAFETY: We're truncating out all the invalid bits, so the remaining
472 // ones must be valid.
473 unsafe { BitFlags::from_bits_unchecked(bits & T::ALL_BITS) }
474 }
475
476 /// Create a new BitFlags unsafely, without checking if the bits form
477 /// a valid bit pattern for the type.
478 ///
479 /// Consider using [`from_bits`][BitFlags::from_bits]
480 /// or [`from_bits_truncate`][BitFlags::from_bits_truncate] instead.
481 ///
482 /// # Safety
483 ///
484 /// All bits set in `val` must correspond to a value of the enum.
485 #[must_use]
486 #[inline(always)]
487 pub unsafe fn from_bits_unchecked(val: T::Numeric) -> Self {
488 BitFlags {
489 val,
490 marker: PhantomData,
491 }
492 }
493
494 /// Turn a `T` into a `BitFlags<T>`. Also available as `flag.into()`.
495 #[must_use]
496 #[inline(always)]
497 pub fn from_flag(flag: T) -> Self {
498 // SAFETY: A value of the underlying enum is valid by definition.
499 unsafe { Self::from_bits_unchecked(flag.bits()) }
500 }
501
502 /// Create a `BitFlags` with no flags set (in other words, with a value of `0`).
503 ///
504 /// See also: [`BitFlag::empty`], a convenience reexport;
505 /// [`BitFlags::EMPTY`], the same functionality available
506 /// as a constant for `const fn` code.
507 ///
508 /// ```
509 /// # use enumflags2::{bitflags, BitFlags};
510 /// #[bitflags]
511 /// #[repr(u8)]
512 /// #[derive(Clone, Copy, PartialEq, Eq)]
513 /// enum MyFlag {
514 /// One = 1 << 0,
515 /// Two = 1 << 1,
516 /// Three = 1 << 2,
517 /// }
518 ///
519 /// let empty: BitFlags<MyFlag> = BitFlags::empty();
520 /// assert!(empty.is_empty());
521 /// assert_eq!(empty.contains(MyFlag::One), false);
522 /// assert_eq!(empty.contains(MyFlag::Two), false);
523 /// assert_eq!(empty.contains(MyFlag::Three), false);
524 /// ```
525 #[inline(always)]
526 pub fn empty() -> Self {
527 Self::EMPTY
528 }
529
530 /// Create a `BitFlags` with all flags set.
531 ///
532 /// See also: [`BitFlag::all`], a convenience reexport;
533 /// [`BitFlags::ALL`], the same functionality available
534 /// as a constant for `const fn` code.
535 ///
536 /// ```
537 /// # use enumflags2::{bitflags, BitFlags};
538 /// #[bitflags]
539 /// #[repr(u8)]
540 /// #[derive(Clone, Copy, PartialEq, Eq)]
541 /// enum MyFlag {
542 /// One = 1 << 0,
543 /// Two = 1 << 1,
544 /// Three = 1 << 2,
545 /// }
546 ///
547 /// let empty: BitFlags<MyFlag> = BitFlags::all();
548 /// assert!(empty.is_all());
549 /// assert_eq!(empty.contains(MyFlag::One), true);
550 /// assert_eq!(empty.contains(MyFlag::Two), true);
551 /// assert_eq!(empty.contains(MyFlag::Three), true);
552 /// ```
553 #[inline(always)]
554 pub fn all() -> Self {
555 Self::ALL
556 }
557
558 /// An empty `BitFlags`. Equivalent to [`empty()`][BitFlags::empty],
559 /// but works in a const context.
560 pub const EMPTY: Self = BitFlags {
561 val: T::EMPTY,
562 marker: PhantomData,
563 };
564
565 /// A `BitFlags` with all flags set. Equivalent to [`all()`][BitFlags::all],
566 /// but works in a const context.
567 pub const ALL: Self = BitFlags {
568 val: T::ALL_BITS,
569 marker: PhantomData,
570 };
571
572 /// A [`ConstToken`] for this type of flag.
573 pub const CONST_TOKEN: ConstToken<T, T::Numeric> = ConstToken(Self::ALL);
574
575 /// Returns true if all flags are set
576 #[inline(always)]
577 pub fn is_all(self) -> bool {
578 self.val == T::ALL_BITS
579 }
580
581 /// Returns true if no flag is set
582 #[inline(always)]
583 pub fn is_empty(self) -> bool {
584 self.val == T::EMPTY
585 }
586
587 /// Returns the number of flags set.
588 #[inline(always)]
589 pub fn len(self) -> usize {
590 self.val.count_ones() as usize
591 }
592
593 /// If exactly one flag is set, the flag is returned. Otherwise, returns `None`.
594 ///
595 /// See also [`Itertools::exactly_one`](https://docs.rs/itertools/latest/itertools/trait.Itertools.html#method.exactly_one).
596 #[inline(always)]
597 pub fn exactly_one(self) -> Option<T> {
598 if self.val.is_power_of_two() {
599 // SAFETY: By the invariant of the BitFlags type, all bits are valid
600 // in isolation for the underlying enum.
601 Some(unsafe { core::mem::transmute_copy(&self.val) })
602 } else {
603 None
604 }
605 }
606
607 /// Returns the underlying bitwise value.
608 ///
609 /// ```
610 /// # use enumflags2::{bitflags, BitFlags};
611 /// #[bitflags]
612 /// #[repr(u8)]
613 /// #[derive(Clone, Copy)]
614 /// enum Flags {
615 /// Foo = 1 << 0,
616 /// Bar = 1 << 1,
617 /// }
618 ///
619 /// let both_flags = Flags::Foo | Flags::Bar;
620 /// assert_eq!(both_flags.bits(), 0b11);
621 /// ```
622 #[inline(always)]
623 pub fn bits(self) -> T::Numeric {
624 self.val
625 }
626
627 /// Returns true if at least one flag is shared.
628 #[inline(always)]
629 pub fn intersects<B: Into<BitFlags<T>>>(self, other: B) -> bool {
630 (self.bits() & other.into().bits()) != Self::EMPTY.val
631 }
632
633 /// Returns true if all flags are contained.
634 #[inline(always)]
635 pub fn contains<B: Into<BitFlags<T>>>(self, other: B) -> bool {
636 let other = other.into();
637 (self.bits() & other.bits()) == other.bits()
638 }
639
640 /// Toggles the matching bits
641 #[inline(always)]
642 pub fn toggle<B: Into<BitFlags<T>>>(&mut self, other: B) {
643 *self ^= other.into();
644 }
645
646 /// Inserts the flags into the BitFlag
647 #[inline(always)]
648 pub fn insert<B: Into<BitFlags<T>>>(&mut self, other: B) {
649 *self |= other.into();
650 }
651
652 /// Removes the matching flags
653 #[inline(always)]
654 pub fn remove<B: Into<BitFlags<T>>>(&mut self, other: B) {
655 *self &= !other.into();
656 }
657
658 /// Returns an iterator that yields each set flag
659 #[inline]
660 pub fn iter(self) -> Iter<T> {
661 Iter {
662 rest: self,
663 }
664 }
665}
666
667impl<T: BitFlag> IntoIterator for BitFlags<T> {
668 type IntoIter = Iter<T>;
669 type Item = T;
670
671 fn into_iter(self) -> Self::IntoIter {
672 self.iter()
673 }
674}
675
676/// Iterator that yields each set flag.
677#[derive(Clone, Debug)]
678pub struct Iter<T: BitFlag> {
679 rest: BitFlags<T>,
680}
681
682impl<T> Iterator for Iter<T>
683where
684 T: BitFlag,
685{
686 type Item = T;
687
688 fn next(&mut self) -> Option<Self::Item> {
689 if self.rest.is_empty() {
690 None
691 } else {
692 // SAFETY: `flag` will be a single bit, because
693 // x & -x = x & (~x + 1), and the increment causes only one 0 -> 1 transition.
694 // The invariant of `from_bits_unchecked` is satisfied, because bits & x
695 // is a subset of bits, which we know are the valid bits.
696 unsafe {
697 let bits = self.rest.bits();
698 let flag: T::Numeric = bits & bits.wrapping_neg();
699 let flag: T = core::mem::transmute_copy(&flag);
700 self.rest = BitFlags::from_bits_unchecked(bits & (bits - BitFlagNum::ONE));
701 Some(flag)
702 }
703 }
704 }
705
706 fn size_hint(&self) -> (usize, Option<usize>) {
707 let l = self.rest.len();
708 (l, Some(l))
709 }
710}
711
712impl<T> ExactSizeIterator for Iter<T>
713where
714 T: BitFlag,
715{
716 fn len(&self) -> usize {
717 self.rest.len()
718 }
719}
720
721impl<T: BitFlag> FusedIterator for Iter<T> {}
722
723for_each_uint! { $ty $hide_docs =>
724 impl<T> BitFlags<T, $ty> {
725 /// Create a new BitFlags unsafely, without checking if the bits form
726 /// a valid bit pattern for the type.
727 ///
728 /// Const variant of
729 /// [`from_bits_unchecked`][BitFlags::from_bits_unchecked].
730 ///
731 /// Consider using
732 /// [`from_bits_truncate_c`][BitFlags::from_bits_truncate_c] instead.
733 ///
734 /// # Safety
735 ///
736 /// All bits set in `val` must correspond to a value of the enum.
737 #[must_use]
738 #[inline(always)]
739 $(#[$hide_docs])?
740 pub const unsafe fn from_bits_unchecked_c(
741 val: $ty, const_token: ConstToken<T, $ty>
742 ) -> Self {
743 let _ = const_token;
744 BitFlags {
745 val,
746 marker: PhantomData,
747 }
748 }
749
750 /// Create a `BitFlags<T>` from an underlying bitwise value. If any
751 /// invalid bits are set, ignore them.
752 ///
753 /// ```
754 /// # use enumflags2::{bitflags, BitFlags};
755 /// #[bitflags]
756 /// #[repr(u8)]
757 /// #[derive(Clone, Copy, Debug, PartialEq, Eq)]
758 /// enum MyFlag {
759 /// One = 1 << 0,
760 /// Two = 1 << 1,
761 /// Three = 1 << 2,
762 /// }
763 ///
764 /// const FLAGS: BitFlags<MyFlag> =
765 /// BitFlags::<MyFlag>::from_bits_truncate_c(0b10101010, BitFlags::CONST_TOKEN);
766 /// assert_eq!(FLAGS, MyFlag::Two);
767 /// ```
768 #[must_use]
769 #[inline(always)]
770 $(#[$hide_docs])?
771 pub const fn from_bits_truncate_c(
772 bits: $ty, const_token: ConstToken<T, $ty>
773 ) -> Self {
774 BitFlags {
775 val: bits & const_token.0.val,
776 marker: PhantomData,
777 }
778 }
779
780 /// Bitwise OR — return value contains flag if either argument does.
781 ///
782 /// Also available as `a | b`, but operator overloads are not usable
783 /// in `const fn`s at the moment.
784 #[must_use]
785 #[inline(always)]
786 $(#[$hide_docs])?
787 pub const fn union_c(self, other: Self) -> Self {
788 BitFlags {
789 val: self.val | other.val,
790 marker: PhantomData,
791 }
792 }
793
794 /// Bitwise AND — return value contains flag if both arguments do.
795 ///
796 /// Also available as `a & b`, but operator overloads are not usable
797 /// in `const fn`s at the moment.
798 #[must_use]
799 #[inline(always)]
800 $(#[$hide_docs])?
801 pub const fn intersection_c(self, other: Self) -> Self {
802 BitFlags {
803 val: self.val & other.val,
804 marker: PhantomData,
805 }
806 }
807
808 /// Bitwise NOT — return value contains flag if argument doesn't.
809 ///
810 /// Also available as `!a`, but operator overloads are not usable
811 /// in `const fn`s at the moment.
812 ///
813 /// Moreover, due to `const fn` limitations, `not_c` needs a
814 /// [`ConstToken`] as an argument.
815 ///
816 /// ```
817 /// # use enumflags2::{bitflags, BitFlags, make_bitflags};
818 /// #[bitflags]
819 /// #[repr(u8)]
820 /// #[derive(Clone, Copy, Debug, PartialEq, Eq)]
821 /// enum MyFlag {
822 /// One = 1 << 0,
823 /// Two = 1 << 1,
824 /// Three = 1 << 2,
825 /// }
826 ///
827 /// const FLAGS: BitFlags<MyFlag> = make_bitflags!(MyFlag::{One | Two});
828 /// const NEGATED: BitFlags<MyFlag> = FLAGS.not_c(BitFlags::CONST_TOKEN);
829 /// assert_eq!(NEGATED, MyFlag::Three);
830 /// ```
831 #[must_use]
832 #[inline(always)]
833 $(#[$hide_docs])?
834 pub const fn not_c(self, const_token: ConstToken<T, $ty>) -> Self {
835 BitFlags {
836 val: !self.val & const_token.0.val,
837 marker: PhantomData,
838 }
839 }
840
841 /// Returns the underlying bitwise value.
842 ///
843 /// `const` variant of [`bits`][BitFlags::bits].
844 #[inline(always)]
845 $(#[$hide_docs])?
846 pub const fn bits_c(self) -> $ty {
847 self.val
848 }
849 }
850}
851
852impl<T, N: PartialEq> cmp::PartialEq for BitFlags<T, N> {
853 #[inline(always)]
854 fn eq(&self, other: &Self) -> bool {
855 self.val == other.val
856 }
857}
858
859// Clippy complains when Hash is derived while PartialEq is implemented manually
860impl<T, N: core::hash::Hash> core::hash::Hash for BitFlags<T, N> {
861 #[inline(always)]
862 fn hash<H: core::hash::Hasher>(&self, state: &mut H) {
863 self.val.hash(state)
864 }
865}
866
867impl<T> cmp::PartialEq<T> for BitFlags<T>
868where
869 T: BitFlag,
870{
871 #[inline(always)]
872 fn eq(&self, other: &T) -> bool {
873 self.bits() == Into::<Self>::into(*other).bits()
874 }
875}
876
877impl<T, B> ops::BitOr<B> for BitFlags<T>
878where
879 T: BitFlag,
880 B: Into<BitFlags<T>>,
881{
882 type Output = BitFlags<T>;
883 #[inline(always)]
884 fn bitor(self, other: B) -> BitFlags<T> {
885 // SAFETY: The two operands are known to be composed of valid bits,
886 // and 0 | 0 = 0 in the columns of the invalid bits.
887 unsafe { BitFlags::from_bits_unchecked(self.bits() | other.into().bits()) }
888 }
889}
890
891impl<T, B> ops::BitAnd<B> for BitFlags<T>
892where
893 T: BitFlag,
894 B: Into<BitFlags<T>>,
895{
896 type Output = BitFlags<T>;
897 #[inline(always)]
898 fn bitand(self, other: B) -> BitFlags<T> {
899 // SAFETY: The two operands are known to be composed of valid bits,
900 // and 0 & 0 = 0 in the columns of the invalid bits.
901 unsafe { BitFlags::from_bits_unchecked(self.bits() & other.into().bits()) }
902 }
903}
904
905impl<T, B> ops::BitXor<B> for BitFlags<T>
906where
907 T: BitFlag,
908 B: Into<BitFlags<T>>,
909{
910 type Output = BitFlags<T>;
911 #[inline(always)]
912 fn bitxor(self, other: B) -> BitFlags<T> {
913 // SAFETY: The two operands are known to be composed of valid bits,
914 // and 0 ^ 0 = 0 in the columns of the invalid bits.
915 unsafe { BitFlags::from_bits_unchecked(self.bits() ^ other.into().bits()) }
916 }
917}
918
919impl<T, B> ops::BitOrAssign<B> for BitFlags<T>
920where
921 T: BitFlag,
922 B: Into<BitFlags<T>>,
923{
924 #[inline(always)]
925 fn bitor_assign(&mut self, other: B) {
926 *self = *self | other;
927 }
928}
929
930impl<T, B> ops::BitAndAssign<B> for BitFlags<T>
931where
932 T: BitFlag,
933 B: Into<BitFlags<T>>,
934{
935 #[inline(always)]
936 fn bitand_assign(&mut self, other: B) {
937 *self = *self & other;
938 }
939}
940impl<T, B> ops::BitXorAssign<B> for BitFlags<T>
941where
942 T: BitFlag,
943 B: Into<BitFlags<T>>,
944{
945 #[inline(always)]
946 fn bitxor_assign(&mut self, other: B) {
947 *self = *self ^ other;
948 }
949}
950
951impl<T> ops::Not for BitFlags<T>
952where
953 T: BitFlag,
954{
955 type Output = BitFlags<T>;
956 #[inline(always)]
957 fn not(self) -> BitFlags<T> {
958 BitFlags::from_bits_truncate(!self.bits())
959 }
960}
961
962impl<T, B> FromIterator<B> for BitFlags<T>
963where
964 T: BitFlag,
965 B: Into<BitFlags<T>>,
966{
967 #[inline]
968 fn from_iter<I>(it: I) -> BitFlags<T>
969 where
970 I: IntoIterator<Item = B>,
971 {
972 it.into_iter()
973 .fold(BitFlags::empty(), |acc, flag| acc | flag)
974 }
975}
976
977impl<T, B> Extend<B> for BitFlags<T>
978where
979 T: BitFlag,
980 B: Into<BitFlags<T>>,
981{
982 #[inline]
983 fn extend<I>(&mut self, it: I)
984 where
985 I: IntoIterator<Item = B>,
986 {
987 *self = it.into_iter().fold(*self, |acc, flag| acc | flag)
988 }
989}
990
991#[cfg(feature = "serde")]
992mod impl_serde {
993 use super::{BitFlag, BitFlags};
994 use serde::de::{Error, Unexpected};
995 use serde::{Deserialize, Serialize};
996
997 impl<'a, T> Deserialize<'a> for BitFlags<T>
998 where
999 T: BitFlag,
1000 T::Numeric: Deserialize<'a> + Into<u64>,
1001 {
1002 fn deserialize<D: serde::Deserializer<'a>>(d: D) -> Result<Self, D::Error> {
1003 let val = T::Numeric::deserialize(d)?;
1004 Self::from_bits(val).map_err(|_| {
1005 D::Error::invalid_value(
1006 Unexpected::Unsigned(val.into()),
1007 &"valid bit representation",
1008 )
1009 })
1010 }
1011 }
1012
1013 impl<T> Serialize for BitFlags<T>
1014 where
1015 T: BitFlag,
1016 T::Numeric: Serialize,
1017 {
1018 fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
1019 T::Numeric::serialize(&self.val, s)
1020 }
1021 }
1022}