Skip to main content

enumset/
impl_set.rs

1use crate::repr::EnumSetTypeRepr;
2use crate::traits::{EnumSetConstHelper, EnumSetType};
3use crate::EnumSetTypeWithRepr;
4use core::cmp::Ordering;
5use core::fmt::{Debug, Display, Formatter};
6use core::hash::{Hash, Hasher};
7use core::iter::Sum;
8use core::ops::{
9    BitAnd, BitAndAssign, BitOr, BitOrAssign, BitXor, BitXorAssign, Not, Sub, SubAssign,
10};
11
12#[cfg(feature = "serde")]
13use serde::{Deserialize, Serialize};
14
15/// An efficient set type for enums.
16///
17/// It is implemented using a bitset stored using the smallest integer that can fit all bits
18/// in the underlying enum. In general, an enum variant with a discriminant of `n` is stored in
19/// the `n + 1`th least significant bit (corresponding with a mask of, e.g. `1 << enum as u32`).
20///
21/// # Numeric Representation
22///
23/// `EnumSet` is internally implemented using integer types, and as such can be easily converted
24/// from and to numbers.
25///
26/// Each bit of the underlying integer corresponds to at most one particular enum variant. If the
27/// corresponding bit for a variant is set, it is present in the set. Bits that do not correspond
28/// to any variant are always unset.
29///
30/// By default, each enum variant is stored in a bit corresponding to its discriminant. An enum
31/// variant with a discriminant of `n` is stored in the `n + 1`th least significant bit
32/// (corresponding to a mask of, e.g. `1 << enum as u32`).
33///
34/// The [`#[enumset(map = "…")]`](derive@crate::EnumSetType#mapping-options) attribute can be used
35/// to control this mapping.
36///
37/// # Array Representation
38///
39/// Sets with 64 or more variants are instead stored with an underlying array of `u64`s. This is
40/// treated as if it was a single large integer. The `n`th least significant bit of this integer
41/// is stored in the `n % 64`th least significant bit of the `n / 64`th element in the array.
42///
43/// # Serialization
44///
45/// When the `serde` feature is enabled, `EnumSet`s can be serialized and deserialized using
46/// the `serde` crate.
47///
48/// By default, `EnumSet` is serialized by directly writing out a single integer containing the
49/// numeric representation of the bitset. The integer type used is the smallest one that can fit
50/// the largest variant in the enum. If no integer type is large enough, instead the `EnumSet` is
51/// serialized as an array of `u64`s containing the array representation. Unknown bits are ignored
52/// and silently removed from the bitset when deserializing.
53///
54/// The exact serialization format can be controlled with additional attributes on the enum type.
55/// For more information, see the documentation for
56/// [Serialization Options](derive@crate::EnumSetType#serialization-options).
57///
58/// # FFI Safety
59///
60/// By default, there are no guarantees about the underlying representation of an `EnumSet`. To use
61/// them safely across FFI boundaries, the
62/// [`#[enumset(repr = "…")]`](derive@crate::EnumSetType#representation-options) attribute must be
63/// used with a primitive integer type. For example:
64///
65/// ```
66/// # use enumset::*;
67/// #
68/// # mod ffi_impl {
69/// #     // This example “foreign” function is actually written in Rust, but for the sake
70/// #     // of example, we'll pretend it's written in C.
71/// #     #[no_mangle]
72/// #     extern "C" fn some_foreign_function(set: u32) -> u32 {
73/// #         set & 0b100
74/// #     }
75/// # }
76/// #
77/// extern "C" {
78///     // This function is written in C like:
79///     // uint32_t some_foreign_function(uint32_t set) { … }
80///     fn some_foreign_function(set: EnumSet<MyEnum>) -> EnumSet<MyEnum>;
81/// }
82///
83/// #[derive(Debug, EnumSetType)]
84/// #[enumset(repr = "u32")]
85/// enum MyEnum { A, B, C }
86///
87/// let set: EnumSet<MyEnum> = enum_set!(MyEnum::A | MyEnum::C);
88///
89/// let new_set: EnumSet<MyEnum> = unsafe { some_foreign_function(set) };
90/// assert_eq!(new_set, enum_set!(MyEnum::C));
91/// ```
92///
93/// When an `EnumSet<T>` is received via FFI, all bits that don't correspond to an enum variant
94/// of `T` must be set to `0`. Behavior is **undefined** if any of these bits are set to `1`.
95#[derive(Copy, Clone, PartialEq, Eq)]
96#[repr(transparent)]
97pub struct EnumSet<T: EnumSetType> {
98    pub(crate) repr: T::Repr,
99}
100
101//region EnumSet operations
102impl<T: EnumSetType> EnumSet<T> {
103    const EMPTY_REPR: Self = EnumSet { repr: T::Repr::EMPTY };
104    const ALL_REPR: Self = EnumSet { repr: T::ALL_BITS };
105
106    /// Creates an empty `EnumSet`.
107    #[inline(always)]
108    pub const fn new() -> Self {
109        Self::EMPTY_REPR
110    }
111
112    /// Creates an empty `EnumSet`.
113    ///
114    /// This is an alias for [`EnumSet::new`].
115    #[inline(always)]
116    pub const fn empty() -> Self {
117        Self::EMPTY_REPR
118    }
119
120    /// Returns an `EnumSet` containing all valid variants of the enum.
121    #[inline(always)]
122    pub const fn all() -> Self {
123        Self::ALL_REPR
124    }
125
126    /// Total number of bits used by this type. Note that the actual amount of space used is
127    /// rounded up to the next highest integer type (`u8`, `u16`, `u32`, `u64`, or `u128`).
128    ///
129    /// This is the same as [`EnumSet::variant_count`] except in enums with "sparse" variants.
130    /// (e.g. `enum Foo { A = 10, B = 20 }`)
131    #[inline(always)]
132    pub const fn bit_width() -> u32 {
133        T::BIT_WIDTH
134    }
135
136    /// The number of valid variants that this type can contain.
137    ///
138    /// This is the same as [`EnumSet::bit_width`] except in enums with "sparse" variants.
139    /// (e.g. `enum Foo { A = 10, B = 20 }`)
140    #[inline(always)]
141    pub const fn variant_count() -> u32 {
142        T::VARIANT_COUNT
143    }
144
145    // SEMVER: On semver major change, make the other parameter into a `impl Into<>`
146    set_common_methods!(T, T::Repr, Self);
147
148    /// Returns a set containing all enum variants not in this set.
149    #[inline(always)]
150    pub fn complement(&self) -> Self {
151        Self { repr: !self.repr & T::ALL_BITS }
152    }
153
154    /// Adds all elements in another set to this one.
155    #[inline(always)]
156    pub fn insert_all(&mut self, other: Self) {
157        self.repr = self.repr | other.repr
158    }
159
160    /// Removes all values in another set from this one.
161    #[inline(always)]
162    pub fn remove_all(&mut self, other: Self) {
163        self.repr = self.repr.and_not(other.repr);
164    }
165}
166
167/// A helper type used for constant evaluation of enum operations.
168#[doc(hidden)]
169pub struct EnumSetInitHelper;
170impl EnumSetInitHelper {
171    /// Just returns this value - the version for the enums themselves would wrap it into an
172    /// enumset.
173    pub const fn const_only<T>(&self, value: T) -> T {
174        value
175    }
176}
177
178#[doc(hidden)]
179unsafe impl<T: EnumSetType> EnumSetConstHelper for EnumSet<T> {
180    type ConstInitHelper = EnumSetInitHelper;
181    const CONST_INIT_HELPER: Self::ConstInitHelper = EnumSetInitHelper;
182
183    type ConstOpHelper = T::ConstOpHelper;
184    const CONST_OP_HELPER: Self::ConstOpHelper = T::CONST_OP_HELPER;
185}
186
187set_common_impls!(EnumSet, EnumSetType);
188
189#[cfg(feature = "defmt")]
190impl<T: EnumSetType + defmt::Format> defmt::Format for EnumSet<T> {
191    fn format(&self, f: defmt::Formatter) {
192        let mut i = self.iter();
193        if let Some(v) = i.next() {
194            defmt::write!(f, "{}", v);
195            for v in i {
196                defmt::write!(f, " | {}", v);
197            }
198        }
199    }
200}
201
202#[cfg(feature = "serde")]
203impl<T: EnumSetType> Serialize for EnumSet<T> {
204    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
205        T::serialize(*self, serializer)
206    }
207}
208
209#[cfg(feature = "serde")]
210impl<'de, T: EnumSetType> Deserialize<'de> for EnumSet<T> {
211    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
212        T::deserialize(deserializer)
213    }
214}
215//endregion
216
217//region Deprecated functions
218/// This impl contains all outdated or deprecated functions.
219impl<T: EnumSetType> EnumSet<T> {
220    /// An empty `EnumSet`.
221    ///
222    /// This is deprecated because [`EnumSet::empty`] is now `const`.
223    #[deprecated = "Use `EnumSet::empty()` instead."]
224    pub const EMPTY: Self = Self::EMPTY_REPR;
225
226    /// An `EnumSet` containing all valid variants of the enum.
227    ///
228    /// This is deprecated because [`EnumSet::all`] is now `const`.
229    #[deprecated = "Use `EnumSet::all()` instead."]
230    pub const ALL: Self = Self::ALL_REPR;
231}
232//endregion
233
234//region EnumSet conversions
235impl<T: EnumSetType + EnumSetTypeWithRepr> EnumSet<T> {
236    /// Returns a `T::Repr` representing the elements of this set.
237    ///
238    /// Unlike the other `as_*` methods, this method is zero-cost and guaranteed not to fail,
239    /// panic or truncate any bits.
240    ///
241    /// In order to use this method, the definition of `T` must have an
242    /// [`#[enumset(repr = "…")]`](derive@crate::EnumSetType#representation-options) annotation
243    /// with a primitive integer type.
244    #[inline(always)]
245    pub const fn as_repr(&self) -> <T as EnumSetTypeWithRepr>::Repr {
246        self.repr
247    }
248
249    /// Constructs a bitset from a `T::Repr` without checking for invalid bits.
250    ///
251    /// Unlike the other `from_*` methods, this method is zero-cost and guaranteed not to fail,
252    /// panic or truncate any bits, provided the conditions under “Safety” are upheld.
253    ///
254    /// In order to use this method, the definition of `T` must have an
255    /// [`#[enumset(repr = "…")]`](derive@crate::EnumSetType#representation-options) annotation
256    /// with a primitive integer type.
257    ///
258    /// # Safety
259    ///
260    /// All bits in the provided parameter `bits` that don't correspond to an enum variant of
261    /// `T` must be set to `0`. Behavior is **undefined** if any of these bits are set to `1`.
262    #[inline(always)]
263    pub unsafe fn from_repr_unchecked(bits: <T as EnumSetTypeWithRepr>::Repr) -> Self {
264        Self { repr: bits }
265    }
266
267    /// Constructs a bitset from a `T::Repr`.
268    ///
269    /// If a bit that doesn't correspond to an enum variant is set, this
270    /// method will panic.
271    ///
272    /// In order to use this method, the definition of `T` must have an
273    /// [`#[enumset(repr = "…")]`](derive@crate::EnumSetType#representation-options) annotation
274    /// with a primitive integer type.
275    #[inline(always)]
276    pub fn from_repr(bits: <T as EnumSetTypeWithRepr>::Repr) -> Self {
277        Self::try_from_repr(bits).expect("Bitset contains invalid variants.")
278    }
279
280    /// Attempts to construct a bitset from a `T::Repr`.
281    ///
282    /// If a bit that doesn't correspond to an enum variant is set, this
283    /// method will return `None`.
284    ///
285    /// In order to use this method, the definition of `T` must have an
286    /// [`#[enumset(repr = "…")]`](derive@crate::EnumSetType#representation-options) annotation
287    /// with a primitive integer type.
288    #[inline(always)]
289    pub fn try_from_repr(bits: <T as EnumSetTypeWithRepr>::Repr) -> Option<Self> {
290        let mask = Self::all().repr;
291        if bits.and_not(mask).is_empty() {
292            Some(EnumSet { repr: bits })
293        } else {
294            None
295        }
296    }
297
298    /// Constructs a bitset from a `T::Repr`, ignoring invalid variants.
299    ///
300    /// In order to use this method, the definition of `T` must have an
301    /// [`#[enumset(repr = "…")]`](derive@crate::EnumSetType#representation-options) annotation
302    /// with a primitive integer type.
303    #[inline(always)]
304    pub fn from_repr_truncated(bits: <T as EnumSetTypeWithRepr>::Repr) -> Self {
305        let mask = Self::all().as_repr();
306        let bits = bits & mask;
307        EnumSet { repr: bits }
308    }
309}
310
311/// Helper macro for generating conversion functions.
312macro_rules! conversion_impls {
313    (
314        $(for_num!(
315            $underlying:ty, $underlying_str:expr,
316            $from_fn:ident $to_fn:ident $try_from_fn:ident $try_to_fn:ident,
317            $from:ident $try_from:ident $from_truncated:ident $from_unchecked:ident,
318            $to:ident $try_to:ident $to_truncated:ident
319        );)*
320    ) => {
321        impl<T: EnumSetType> EnumSet<T> {$(
322            #[doc = "Returns a `"]
323            #[doc = $underlying_str]
324            #[doc = "` representing the elements of this set.\n\nIf the underlying bitset will \
325                     not fit in a `"]
326            #[doc = $underlying_str]
327            #[doc = "`, this method will panic."]
328            #[inline(always)]
329            pub fn $to(&self) -> $underlying {
330                self.$try_to().expect("Bitset will not fit into this type.")
331            }
332
333            #[doc = "Tries to return a `"]
334            #[doc = $underlying_str]
335            #[doc = "` representing the elements of this set.\n\nIf the underlying bitset will \
336                     not fit in a `"]
337            #[doc = $underlying_str]
338            #[doc = "`, this method will return `None`."]
339            #[inline(always)]
340            pub fn $try_to(&self) -> Option<$underlying> {
341                EnumSetTypeRepr::$try_to_fn(&self.repr)
342            }
343
344            #[doc = "Returns a truncated `"]
345            #[doc = $underlying_str]
346            #[doc = "` representing the elements of this set.\n\nIf the underlying bitset will \
347                     not fit in a `"]
348            #[doc = $underlying_str]
349            #[doc = "`, this method will truncate any bits that don't fit."]
350            #[inline(always)]
351            pub fn $to_truncated(&self) -> $underlying {
352                EnumSetTypeRepr::$to_fn(&self.repr)
353            }
354
355            #[doc = "Constructs a bitset from a `"]
356            #[doc = $underlying_str]
357            #[doc = "`.\n\nIf a bit that doesn't correspond to an enum variant is set, this \
358                     method will panic."]
359            #[inline(always)]
360            pub fn $from(bits: $underlying) -> Self {
361                Self::$try_from(bits).expect("Bitset contains invalid variants.")
362            }
363
364            #[doc = "Attempts to construct a bitset from a `"]
365            #[doc = $underlying_str]
366            #[doc = "`.\n\nIf a bit that doesn't correspond to an enum variant is set, this \
367                     method will return `None`."]
368            #[inline(always)]
369            pub fn $try_from(bits: $underlying) -> Option<Self> {
370                let bits = T::Repr::$try_from_fn(bits);
371                let mask = T::ALL_BITS;
372                bits.and_then(|bits| if bits.and_not(mask).is_empty() {
373                    Some(EnumSet { repr: bits })
374                } else {
375                    None
376                })
377            }
378
379            #[doc = "Constructs a bitset from a `"]
380            #[doc = $underlying_str]
381            #[doc = "`, ignoring bits that do not correspond to a variant."]
382            #[inline(always)]
383            pub fn $from_truncated(bits: $underlying) -> Self {
384                let mask = Self::all().$to_truncated();
385                let bits = <T::Repr as EnumSetTypeRepr>::$from_fn(bits & mask);
386                EnumSet { repr: bits }
387            }
388
389            #[doc = "Constructs a bitset from a `"]
390            #[doc = $underlying_str]
391            #[doc = "`, without checking for invalid bits."]
392            ///
393            /// # Safety
394            ///
395            /// All bits in the provided parameter `bits` that don't correspond to an enum variant
396            /// of `T` must be set to `0`. Behavior is **undefined** if any of these bits are set
397            /// to `1`.
398            #[inline(always)]
399            pub unsafe fn $from_unchecked(bits: $underlying) -> Self {
400                EnumSet { repr: <T::Repr as EnumSetTypeRepr>::$from_fn(bits) }
401            }
402        )*}
403    }
404}
405conversion_impls! {
406    for_num!(u8, "u8",
407             from_u8 to_u8 try_from_u8 try_to_u8,
408             from_u8 try_from_u8 from_u8_truncated from_u8_unchecked,
409             as_u8 try_as_u8 as_u8_truncated);
410    for_num!(u16, "u16",
411             from_u16 to_u16 try_from_u16 try_to_u16,
412             from_u16 try_from_u16 from_u16_truncated from_u16_unchecked,
413             as_u16 try_as_u16 as_u16_truncated);
414    for_num!(u32, "u32",
415             from_u32 to_u32 try_from_u32 try_to_u32,
416             from_u32 try_from_u32 from_u32_truncated from_u32_unchecked,
417             as_u32 try_as_u32 as_u32_truncated);
418    for_num!(u64, "u64",
419             from_u64 to_u64 try_from_u64 try_to_u64,
420             from_u64 try_from_u64 from_u64_truncated from_u64_unchecked,
421             as_u64 try_as_u64 as_u64_truncated);
422    for_num!(u128, "u128",
423             from_u128 to_u128 try_from_u128 try_to_u128,
424             from_u128 try_from_u128 from_u128_truncated from_u128_unchecked,
425             as_u128 try_as_u128 as_u128_truncated);
426    for_num!(usize, "usize",
427             from_usize to_usize try_from_usize try_to_usize,
428             from_usize try_from_usize from_usize_truncated from_usize_unchecked,
429             as_usize try_as_usize as_usize_truncated);
430}
431
432impl<T: EnumSetType> EnumSet<T> {
433    /// Returns a `[u64; O]` representing the elements of this set.
434    ///
435    /// If the underlying bitset will not fit in a `[u64; O]`, this method will panic.
436    pub fn as_array<const O: usize>(&self) -> [u64; O] {
437        self.try_as_array()
438            .expect("Bitset will not fit into this type.")
439    }
440
441    /// Returns a `[u64; O]` representing the elements of this set.
442    ///
443    /// If the underlying bitset will not fit in a `[u64; O]`, this method will instead return
444    /// `None`.
445    pub fn try_as_array<const O: usize>(&self) -> Option<[u64; O]> {
446        self.repr.try_to_u64_array()
447    }
448
449    /// Returns a `[u64; O]` representing the elements of this set.
450    ///
451    /// If the underlying bitset will not fit in a `[u64; O]`, this method will truncate any bits
452    /// that don't fit.
453    pub fn as_array_truncated<const O: usize>(&self) -> [u64; O] {
454        self.repr.to_u64_array()
455    }
456
457    /// Constructs a bitset from a `[u64; O]`.
458    ///
459    /// If a bit that doesn't correspond to an enum variant is set, this method will panic.
460    pub fn from_array<const O: usize>(v: [u64; O]) -> Self {
461        Self::try_from_array(v).expect("Bitset contains invalid variants.")
462    }
463
464    /// Attempts to construct a bitset from a `[u64; O]`.
465    ///
466    /// If a bit that doesn't correspond to an enum variant is set, this method will return `None`.
467    pub fn try_from_array<const O: usize>(bits: [u64; O]) -> Option<Self> {
468        let bits = T::Repr::try_from_u64_array::<O>(bits);
469        let mask = T::ALL_BITS;
470        bits.and_then(|bits| {
471            if bits.and_not(mask).is_empty() {
472                Some(EnumSet { repr: bits })
473            } else {
474                None
475            }
476        })
477    }
478
479    /// Constructs a bitset from a `[u64; O]`, ignoring bits that do not correspond to a variant.
480    pub fn from_array_truncated<const O: usize>(bits: [u64; O]) -> Self {
481        let bits = T::Repr::from_u64_array(bits) & T::ALL_BITS;
482        EnumSet { repr: bits }
483    }
484
485    /// Constructs a bitset from a `[u64; O]`, without checking for invalid bits.
486    ///
487    /// # Safety
488    ///
489    /// All bits in the provided parameter `bits` that don't correspond to an enum variant
490    /// of `T` must be set to `0`. Behavior is **undefined** if any of these bits are set
491    /// to `1`.
492    #[inline(always)]
493    pub unsafe fn from_array_unchecked<const O: usize>(bits: [u64; O]) -> Self {
494        EnumSet { repr: T::Repr::from_u64_array(bits) }
495    }
496
497    /// Returns a `Vec<u64>` representing the elements of this set.
498    #[cfg(feature = "alloc")]
499    #[cfg_attr(docsrs, doc(cfg(feature = "alloc")))]
500    pub fn to_vec(&self) -> alloc::vec::Vec<u64> {
501        let mut vec = alloc::vec![0; T::Repr::PREFERRED_ARRAY_LEN];
502        self.repr.to_u64_slice(&mut vec);
503        vec
504    }
505
506    /// Copies the elements of this set into a `&mut [u64]`.
507    ///
508    /// If the underlying bitset will not fit in the provided slice, this method will panic.
509    pub fn copy_into_slice(&self, data: &mut [u64]) {
510        self.try_copy_into_slice(data)
511            .expect("Bitset will not fit into slice.")
512    }
513
514    /// Copies the elements of this set into a `&mut [u64]`.
515    ///
516    /// If the underlying bitset will not fit in the provided slice, this method will return
517    /// `None`. Otherwise, it will return `Some(())`.
518    #[must_use]
519    pub fn try_copy_into_slice(&self, data: &mut [u64]) -> Option<()> {
520        self.repr.try_to_u64_slice(data)
521    }
522
523    /// Copies the elements of this set into a `&mut [u64]`.
524    ///
525    /// If the underlying bitset will not fit in the provided slice, this method will truncate any
526    /// bits that don't fit.
527    pub fn copy_into_slice_truncated(&self, data: &mut [u64]) {
528        self.repr.to_u64_slice(data)
529    }
530
531    /// Constructs a bitset from a `&[u64]`.
532    ///
533    /// If a bit that doesn't correspond to an enum variant is set, this method will panic.
534    pub fn from_slice(v: &[u64]) -> Self {
535        Self::try_from_slice(v).expect("Bitset contains invalid variants.")
536    }
537
538    /// Attempts to construct a bitset from a `&[u64]`.
539    ///
540    /// If a bit that doesn't correspond to an enum variant is set, this method will return `None`.
541    pub fn try_from_slice(bits: &[u64]) -> Option<Self> {
542        let bits = T::Repr::try_from_u64_slice(bits);
543        let mask = T::ALL_BITS;
544        bits.and_then(|bits| {
545            if bits.and_not(mask).is_empty() {
546                Some(EnumSet { repr: bits })
547            } else {
548                None
549            }
550        })
551    }
552
553    /// Constructs a bitset from a `&[u64]`, ignoring bits that do not correspond to a variant.
554    pub fn from_slice_truncated(bits: &[u64]) -> Self {
555        let bits = T::Repr::from_u64_slice(bits) & T::ALL_BITS;
556        EnumSet { repr: bits }
557    }
558
559    /// Constructs a bitset from a `&[u64]`, without checking for invalid bits.
560    ///
561    /// # Safety
562    ///
563    /// All bits in the provided parameter `bits` that don't correspond to an enum variant
564    /// of `T` must be set to `0`. Behavior is **undefined** if any of these bits are set
565    /// to `1`.
566    #[inline(always)]
567    pub unsafe fn from_slice_unchecked(bits: &[u64]) -> Self {
568        EnumSet { repr: T::Repr::from_u64_slice(bits) }
569    }
570}
571
572impl<T: EnumSetType, const N: usize> From<[T; N]> for EnumSet<T> {
573    fn from(value: [T; N]) -> Self {
574        let mut new = EnumSet::new();
575        for elem in value {
576            new.insert(elem);
577        }
578        new
579    }
580}
581//endregion
582
583//region EnumSet iter
584/// The iterator used by [`EnumSet`]s.
585#[derive(Clone, Debug)]
586pub struct EnumSetIter<T: EnumSetType> {
587    iter: <T::Repr as EnumSetTypeRepr>::Iter,
588}
589impl<T: EnumSetType> EnumSetIter<T> {
590    fn new(set: EnumSet<T>) -> EnumSetIter<T> {
591        EnumSetIter { iter: set.repr.iter() }
592    }
593}
594
595impl<T: EnumSetType> EnumSet<T> {
596    /// Iterates the contents of the set in order from the least significant bit to the most
597    /// significant bit.
598    ///
599    /// Note that iterator invalidation is impossible as the iterator contains a copy of this type,
600    /// rather than holding a reference to it.
601    pub fn iter(&self) -> EnumSetIter<T> {
602        EnumSetIter::new(*self)
603    }
604}
605
606impl<T: EnumSetType> Iterator for EnumSetIter<T> {
607    type Item = T;
608
609    fn next(&mut self) -> Option<Self::Item> {
610        self.iter
611            .next()
612            .map(|x| unsafe { T::enum_from_u32_checked(x) })
613    }
614    fn size_hint(&self) -> (usize, Option<usize>) {
615        self.iter.size_hint()
616    }
617}
618impl<T: EnumSetType> DoubleEndedIterator for EnumSetIter<T> {
619    fn next_back(&mut self) -> Option<Self::Item> {
620        self.iter
621            .next_back()
622            .map(|x| unsafe { T::enum_from_u32_checked(x) })
623    }
624}
625impl<T: EnumSetType> ExactSizeIterator for EnumSetIter<T> {}
626
627set_iterator_impls!(EnumSet, EnumSetType);
628
629impl<T: EnumSetType> IntoIterator for EnumSet<T> {
630    type Item = T;
631    type IntoIter = EnumSetIter<T>;
632
633    fn into_iter(self) -> Self::IntoIter {
634        self.iter()
635    }
636}
637//endregion