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 nth 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 set_common_methods!(T, T::Repr);
146
147 /// Returns a set containing all enum variants not in this set.
148 #[inline(always)]
149 pub fn complement(&self) -> Self {
150 Self { repr: !self.repr & T::ALL_BITS }
151 }
152
153 /// Adds all elements in another set to this one.
154 #[inline(always)]
155 pub fn insert_all(&mut self, other: Self) {
156 self.repr = self.repr | other.repr
157 }
158
159 /// Removes all values in another set from this one.
160 #[inline(always)]
161 pub fn remove_all(&mut self, other: Self) {
162 self.repr = self.repr.and_not(other.repr);
163 }
164}
165
166/// A helper type used for constant evaluation of enum operations.
167#[doc(hidden)]
168pub struct EnumSetInitHelper;
169impl EnumSetInitHelper {
170 /// Just returns this value - the version for the enums themselves would wrap it into an
171 /// enumset.
172 pub const fn const_only<T>(&self, value: T) -> T {
173 value
174 }
175}
176
177#[doc(hidden)]
178unsafe impl<T: EnumSetType> EnumSetConstHelper for EnumSet<T> {
179 type ConstInitHelper = EnumSetInitHelper;
180 const CONST_INIT_HELPER: Self::ConstInitHelper = EnumSetInitHelper;
181
182 type ConstOpHelper = T::ConstOpHelper;
183 const CONST_OP_HELPER: Self::ConstOpHelper = T::CONST_OP_HELPER;
184}
185
186set_common_impls!(EnumSet, EnumSetType);
187
188#[cfg(feature = "defmt")]
189impl<T: EnumSetType + defmt::Format> defmt::Format for EnumSet<T> {
190 fn format(&self, f: defmt::Formatter) {
191 let mut i = self.iter();
192 if let Some(v) = i.next() {
193 defmt::write!(f, "{}", v);
194 for v in i {
195 defmt::write!(f, " | {}", v);
196 }
197 }
198 }
199}
200
201#[cfg(feature = "serde")]
202impl<T: EnumSetType> Serialize for EnumSet<T> {
203 fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
204 T::serialize(*self, serializer)
205 }
206}
207
208#[cfg(feature = "serde")]
209impl<'de, T: EnumSetType> Deserialize<'de> for EnumSet<T> {
210 fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
211 T::deserialize(deserializer)
212 }
213}
214//endregion
215
216//region Deprecated functions
217/// This impl contains all outdated or deprecated functions.
218impl<T: EnumSetType> EnumSet<T> {
219 /// An empty `EnumSet`.
220 ///
221 /// This is deprecated because [`EnumSet::empty`] is now `const`.
222 #[deprecated = "Use `EnumSet::empty()` instead."]
223 pub const EMPTY: Self = Self::EMPTY_REPR;
224
225 /// An `EnumSet` containing all valid variants of the enum.
226 ///
227 /// This is deprecated because [`EnumSet::all`] is now `const`.
228 #[deprecated = "Use `EnumSet::all()` instead."]
229 pub const ALL: Self = Self::ALL_REPR;
230}
231//endregion
232
233//region EnumSet conversions
234impl<T: EnumSetType + EnumSetTypeWithRepr> EnumSet<T> {
235 /// Returns a `T::Repr` representing the elements of this set.
236 ///
237 /// Unlike the other `as_*` methods, this method is zero-cost and guaranteed not to fail,
238 /// panic or truncate any bits.
239 ///
240 /// In order to use this method, the definition of `T` must have an
241 /// [`#[enumset(repr = "…")]`](derive@crate::EnumSetType#representation-options) annotation
242 /// with a primitive integer type.
243 #[inline(always)]
244 pub const fn as_repr(&self) -> <T as EnumSetTypeWithRepr>::Repr {
245 self.repr
246 }
247
248 /// Constructs a bitset from a `T::Repr` without checking for invalid bits.
249 ///
250 /// Unlike the other `from_*` methods, this method is zero-cost and guaranteed not to fail,
251 /// panic or truncate any bits, provided the conditions under “Safety” are upheld.
252 ///
253 /// In order to use this method, the definition of `T` must have an
254 /// [`#[enumset(repr = "…")]`](derive@crate::EnumSetType#representation-options) annotation
255 /// with a primitive integer type.
256 ///
257 /// # Safety
258 ///
259 /// All bits in the provided parameter `bits` that don't correspond to an enum variant of
260 /// `T` must be set to `0`. Behavior is **undefined** if any of these bits are set to `1`.
261 #[inline(always)]
262 pub unsafe fn from_repr_unchecked(bits: <T as EnumSetTypeWithRepr>::Repr) -> Self {
263 Self { repr: bits }
264 }
265
266 /// Constructs a bitset from a `T::Repr`.
267 ///
268 /// If a bit that doesn't correspond to an enum variant is set, this
269 /// method will panic.
270 ///
271 /// In order to use this method, the definition of `T` must have an
272 /// [`#[enumset(repr = "…")]`](derive@crate::EnumSetType#representation-options) annotation
273 /// with a primitive integer type.
274 #[inline(always)]
275 pub fn from_repr(bits: <T as EnumSetTypeWithRepr>::Repr) -> Self {
276 Self::try_from_repr(bits).expect("Bitset contains invalid variants.")
277 }
278
279 /// Attempts to construct a bitset from a `T::Repr`.
280 ///
281 /// If a bit that doesn't correspond to an enum variant is set, this
282 /// method will return `None`.
283 ///
284 /// In order to use this method, the definition of `T` must have an
285 /// [`#[enumset(repr = "…")]`](derive@crate::EnumSetType#representation-options) annotation
286 /// with a primitive integer type.
287 #[inline(always)]
288 pub fn try_from_repr(bits: <T as EnumSetTypeWithRepr>::Repr) -> Option<Self> {
289 let mask = Self::all().repr;
290 if bits.and_not(mask).is_empty() {
291 Some(EnumSet { repr: bits })
292 } else {
293 None
294 }
295 }
296
297 /// Constructs a bitset from a `T::Repr`, ignoring invalid variants.
298 ///
299 /// In order to use this method, the definition of `T` must have an
300 /// [`#[enumset(repr = "…")]`](derive@crate::EnumSetType#representation-options) annotation
301 /// with a primitive integer type.
302 #[inline(always)]
303 pub fn from_repr_truncated(bits: <T as EnumSetTypeWithRepr>::Repr) -> Self {
304 let mask = Self::all().as_repr();
305 let bits = bits & mask;
306 EnumSet { repr: bits }
307 }
308}
309
310/// Helper macro for generating conversion functions.
311macro_rules! conversion_impls {
312 (
313 $(for_num!(
314 $underlying:ty, $underlying_str:expr,
315 $from_fn:ident $to_fn:ident $try_from_fn:ident $try_to_fn:ident,
316 $from:ident $try_from:ident $from_truncated:ident $from_unchecked:ident,
317 $to:ident $try_to:ident $to_truncated:ident
318 );)*
319 ) => {
320 impl<T: EnumSetType> EnumSet<T> {$(
321 #[doc = "Returns a `"]
322 #[doc = $underlying_str]
323 #[doc = "` representing the elements of this set.\n\nIf the underlying bitset will \
324 not fit in a `"]
325 #[doc = $underlying_str]
326 #[doc = "`, this method will panic."]
327 #[inline(always)]
328 pub fn $to(&self) -> $underlying {
329 self.$try_to().expect("Bitset will not fit into this type.")
330 }
331
332 #[doc = "Tries to return a `"]
333 #[doc = $underlying_str]
334 #[doc = "` representing the elements of this set.\n\nIf the underlying bitset will \
335 not fit in a `"]
336 #[doc = $underlying_str]
337 #[doc = "`, this method will return `None`."]
338 #[inline(always)]
339 pub fn $try_to(&self) -> Option<$underlying> {
340 EnumSetTypeRepr::$try_to_fn(&self.repr)
341 }
342
343 #[doc = "Returns a truncated `"]
344 #[doc = $underlying_str]
345 #[doc = "` representing the elements of this set.\n\nIf the underlying bitset will \
346 not fit in a `"]
347 #[doc = $underlying_str]
348 #[doc = "`, this method will truncate any bits that don't fit."]
349 #[inline(always)]
350 pub fn $to_truncated(&self) -> $underlying {
351 EnumSetTypeRepr::$to_fn(&self.repr)
352 }
353
354 #[doc = "Constructs a bitset from a `"]
355 #[doc = $underlying_str]
356 #[doc = "`.\n\nIf a bit that doesn't correspond to an enum variant is set, this \
357 method will panic."]
358 #[inline(always)]
359 pub fn $from(bits: $underlying) -> Self {
360 Self::$try_from(bits).expect("Bitset contains invalid variants.")
361 }
362
363 #[doc = "Attempts to construct a bitset from a `"]
364 #[doc = $underlying_str]
365 #[doc = "`.\n\nIf a bit that doesn't correspond to an enum variant is set, this \
366 method will return `None`."]
367 #[inline(always)]
368 pub fn $try_from(bits: $underlying) -> Option<Self> {
369 let bits = T::Repr::$try_from_fn(bits);
370 let mask = T::ALL_BITS;
371 bits.and_then(|bits| if bits.and_not(mask).is_empty() {
372 Some(EnumSet { repr: bits })
373 } else {
374 None
375 })
376 }
377
378 #[doc = "Constructs a bitset from a `"]
379 #[doc = $underlying_str]
380 #[doc = "`, ignoring bits that do not correspond to a variant."]
381 #[inline(always)]
382 pub fn $from_truncated(bits: $underlying) -> Self {
383 let mask = Self::all().$to_truncated();
384 let bits = <T::Repr as EnumSetTypeRepr>::$from_fn(bits & mask);
385 EnumSet { repr: bits }
386 }
387
388 #[doc = "Constructs a bitset from a `"]
389 #[doc = $underlying_str]
390 #[doc = "`, without checking for invalid bits."]
391 ///
392 /// # Safety
393 ///
394 /// All bits in the provided parameter `bits` that don't correspond to an enum variant
395 /// of `T` must be set to `0`. Behavior is **undefined** if any of these bits are set
396 /// to `1`.
397 #[inline(always)]
398 pub unsafe fn $from_unchecked(bits: $underlying) -> Self {
399 EnumSet { repr: <T::Repr as EnumSetTypeRepr>::$from_fn(bits) }
400 }
401 )*}
402 }
403}
404conversion_impls! {
405 for_num!(u8, "u8",
406 from_u8 to_u8 try_from_u8 try_to_u8,
407 from_u8 try_from_u8 from_u8_truncated from_u8_unchecked,
408 as_u8 try_as_u8 as_u8_truncated);
409 for_num!(u16, "u16",
410 from_u16 to_u16 try_from_u16 try_to_u16,
411 from_u16 try_from_u16 from_u16_truncated from_u16_unchecked,
412 as_u16 try_as_u16 as_u16_truncated);
413 for_num!(u32, "u32",
414 from_u32 to_u32 try_from_u32 try_to_u32,
415 from_u32 try_from_u32 from_u32_truncated from_u32_unchecked,
416 as_u32 try_as_u32 as_u32_truncated);
417 for_num!(u64, "u64",
418 from_u64 to_u64 try_from_u64 try_to_u64,
419 from_u64 try_from_u64 from_u64_truncated from_u64_unchecked,
420 as_u64 try_as_u64 as_u64_truncated);
421 for_num!(u128, "u128",
422 from_u128 to_u128 try_from_u128 try_to_u128,
423 from_u128 try_from_u128 from_u128_truncated from_u128_unchecked,
424 as_u128 try_as_u128 as_u128_truncated);
425 for_num!(usize, "usize",
426 from_usize to_usize try_from_usize try_to_usize,
427 from_usize try_from_usize from_usize_truncated from_usize_unchecked,
428 as_usize try_as_usize as_usize_truncated);
429}
430
431impl<T: EnumSetType> EnumSet<T> {
432 /// Returns a `[u64; O]` representing the elements of this set.
433 ///
434 /// If the underlying bitset will not fit in a `[u64; O]`, this method will panic.
435 pub fn as_array<const O: usize>(&self) -> [u64; O] {
436 self.try_as_array()
437 .expect("Bitset will not fit into this type.")
438 }
439
440 /// Returns a `[u64; O]` representing the elements of this set.
441 ///
442 /// If the underlying bitset will not fit in a `[u64; O]`, this method will instead return
443 /// `None`.
444 pub fn try_as_array<const O: usize>(&self) -> Option<[u64; O]> {
445 self.repr.try_to_u64_array()
446 }
447
448 /// Returns a `[u64; O]` representing the elements of this set.
449 ///
450 /// If the underlying bitset will not fit in a `[u64; O]`, this method will truncate any bits
451 /// that don't fit.
452 pub fn as_array_truncated<const O: usize>(&self) -> [u64; O] {
453 self.repr.to_u64_array()
454 }
455
456 /// Constructs a bitset from a `[u64; O]`.
457 ///
458 /// If a bit that doesn't correspond to an enum variant is set, this method will panic.
459 pub fn from_array<const O: usize>(v: [u64; O]) -> Self {
460 Self::try_from_array(v).expect("Bitset contains invalid variants.")
461 }
462
463 /// Attempts to construct a bitset from a `[u64; O]`.
464 ///
465 /// If a bit that doesn't correspond to an enum variant is set, this method will return `None`.
466 pub fn try_from_array<const O: usize>(bits: [u64; O]) -> Option<Self> {
467 let bits = T::Repr::try_from_u64_array::<O>(bits);
468 let mask = T::ALL_BITS;
469 bits.and_then(|bits| {
470 if bits.and_not(mask).is_empty() {
471 Some(EnumSet { repr: bits })
472 } else {
473 None
474 }
475 })
476 }
477
478 /// Constructs a bitset from a `[u64; O]`, ignoring bits that do not correspond to a variant.
479 pub fn from_array_truncated<const O: usize>(bits: [u64; O]) -> Self {
480 let bits = T::Repr::from_u64_array(bits) & T::ALL_BITS;
481 EnumSet { repr: bits }
482 }
483
484 /// Constructs a bitset from a `[u64; O]`, without checking for invalid bits.
485 ///
486 /// # Safety
487 ///
488 /// All bits in the provided parameter `bits` that don't correspond to an enum variant
489 /// of `T` must be set to `0`. Behavior is **undefined** if any of these bits are set
490 /// to `1`.
491 #[inline(always)]
492 pub unsafe fn from_array_unchecked<const O: usize>(bits: [u64; O]) -> Self {
493 EnumSet { repr: T::Repr::from_u64_array(bits) }
494 }
495
496 /// Returns a `Vec<u64>` representing the elements of this set.
497 #[cfg(feature = "alloc")]
498 #[cfg_attr(docsrs, doc(cfg(feature = "alloc")))]
499 pub fn to_vec(&self) -> alloc::vec::Vec<u64> {
500 let mut vec = alloc::vec![0; T::Repr::PREFERRED_ARRAY_LEN];
501 self.repr.to_u64_slice(&mut vec);
502 vec
503 }
504
505 /// Copies the elements of this set into a `&mut [u64]`.
506 ///
507 /// If the underlying bitset will not fit in the provided slice, this method will panic.
508 pub fn copy_into_slice(&self, data: &mut [u64]) {
509 self.try_copy_into_slice(data)
510 .expect("Bitset will not fit into slice.")
511 }
512
513 /// Copies the elements of this set into a `&mut [u64]`.
514 ///
515 /// If the underlying bitset will not fit in the provided slice, this method will return
516 /// `None`. Otherwise, it will return `Some(())`.
517 #[must_use]
518 pub fn try_copy_into_slice(&self, data: &mut [u64]) -> Option<()> {
519 self.repr.try_to_u64_slice(data)
520 }
521
522 /// Copies the elements of this set into a `&mut [u64]`.
523 ///
524 /// If the underlying bitset will not fit in the provided slice, this method will truncate any
525 /// bits that don't fit.
526 pub fn copy_into_slice_truncated(&self, data: &mut [u64]) {
527 self.repr.to_u64_slice(data)
528 }
529
530 /// Constructs a bitset from a `&[u64]`.
531 ///
532 /// If a bit that doesn't correspond to an enum variant is set, this method will panic.
533 pub fn from_slice(v: &[u64]) -> Self {
534 Self::try_from_slice(v).expect("Bitset contains invalid variants.")
535 }
536
537 /// Attempts to construct a bitset from a `&[u64]`.
538 ///
539 /// If a bit that doesn't correspond to an enum variant is set, this method will return `None`.
540 pub fn try_from_slice(bits: &[u64]) -> Option<Self> {
541 let bits = T::Repr::try_from_u64_slice(bits);
542 let mask = T::ALL_BITS;
543 bits.and_then(|bits| {
544 if bits.and_not(mask).is_empty() {
545 Some(EnumSet { repr: bits })
546 } else {
547 None
548 }
549 })
550 }
551
552 /// Constructs a bitset from a `&[u64]`, ignoring bits that do not correspond to a variant.
553 pub fn from_slice_truncated(bits: &[u64]) -> Self {
554 let bits = T::Repr::from_u64_slice(bits) & T::ALL_BITS;
555 EnumSet { repr: bits }
556 }
557
558 /// Constructs a bitset from a `&[u64]`, without checking for invalid bits.
559 ///
560 /// # Safety
561 ///
562 /// All bits in the provided parameter `bits` that don't correspond to an enum variant
563 /// of `T` must be set to `0`. Behavior is **undefined** if any of these bits are set
564 /// to `1`.
565 #[inline(always)]
566 pub unsafe fn from_slice_unchecked(bits: &[u64]) -> Self {
567 EnumSet { repr: T::Repr::from_u64_slice(bits) }
568 }
569}
570
571impl<T: EnumSetType, const N: usize> From<[T; N]> for EnumSet<T> {
572 fn from(value: [T; N]) -> Self {
573 let mut new = EnumSet::new();
574 for elem in value {
575 new.insert(elem);
576 }
577 new
578 }
579}
580//endregion
581
582//region EnumSet iter
583/// The iterator used by [`EnumSet`]s.
584#[derive(Clone, Debug)]
585pub struct EnumSetIter<T: EnumSetType> {
586 iter: <T::Repr as EnumSetTypeRepr>::Iter,
587}
588impl<T: EnumSetType> EnumSetIter<T> {
589 fn new(set: EnumSet<T>) -> EnumSetIter<T> {
590 EnumSetIter { iter: set.repr.iter() }
591 }
592}
593
594impl<T: EnumSetType> EnumSet<T> {
595 /// Iterates the contents of the set in order from the least significant bit to the most
596 /// significant bit.
597 ///
598 /// Note that iterator invalidation is impossible as the iterator contains a copy of this type,
599 /// rather than holding a reference to it.
600 pub fn iter(&self) -> EnumSetIter<T> {
601 EnumSetIter::new(*self)
602 }
603}
604
605impl<T: EnumSetType> Iterator for EnumSetIter<T> {
606 type Item = T;
607
608 fn next(&mut self) -> Option<Self::Item> {
609 self.iter
610 .next()
611 .map(|x| unsafe { T::enum_from_u32_checked(x) })
612 }
613 fn size_hint(&self) -> (usize, Option<usize>) {
614 self.iter.size_hint()
615 }
616}
617impl<T: EnumSetType> DoubleEndedIterator for EnumSetIter<T> {
618 fn next_back(&mut self) -> Option<Self::Item> {
619 self.iter
620 .next_back()
621 .map(|x| unsafe { T::enum_from_u32_checked(x) })
622 }
623}
624impl<T: EnumSetType> ExactSizeIterator for EnumSetIter<T> {}
625
626set_iterator_impls!(EnumSet, EnumSetType);
627
628impl<T: EnumSetType> IntoIterator for EnumSet<T> {
629 type Item = T;
630 type IntoIter = EnumSetIter<T>;
631
632 fn into_iter(self) -> Self::IntoIter {
633 self.iter()
634 }
635}
636//endregion