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(since = "1.1.4", note = "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(since = "1.1.4", note = "Use `EnumSet::all()` instead.")]
230 pub const ALL: Self = Self::ALL_REPR;
231
232 /// Returns a set containing every element present in either `self` or `other`, but not
233 /// present in both.
234 #[inline(always)]
235 #[deprecated(since = "1.1.13", note = "Use `symmetric_difference` instead.")]
236 pub fn symmetrical_difference(&self, other: Self) -> Self {
237 self.symmetric_difference(other)
238 }
239}
240//endregion
241
242//region EnumSet conversions
243impl<T: EnumSetType + EnumSetTypeWithRepr> EnumSet<T> {
244 /// Returns a `T::Repr` representing the elements of this set.
245 ///
246 /// Unlike the other `as_*` methods, this method is zero-cost and guaranteed not to fail,
247 /// panic or truncate any bits.
248 ///
249 /// In order to use this method, the definition of `T` must have an
250 /// [`#[enumset(repr = "…")]`](derive@crate::EnumSetType#representation-options) annotation
251 /// with a primitive integer type.
252 #[inline(always)]
253 pub const fn as_repr(&self) -> <T as EnumSetTypeWithRepr>::Repr {
254 self.repr
255 }
256
257 /// Constructs a bitset from a `T::Repr` without checking for invalid bits.
258 ///
259 /// Unlike the other `from_*` methods, this method is zero-cost and guaranteed not to fail,
260 /// panic or truncate any bits, provided the conditions under “Safety” are upheld.
261 ///
262 /// In order to use this method, the definition of `T` must have an
263 /// [`#[enumset(repr = "…")]`](derive@crate::EnumSetType#representation-options) annotation
264 /// with a primitive integer type.
265 ///
266 /// # Safety
267 ///
268 /// All bits in the provided parameter `bits` that don't correspond to an enum variant of
269 /// `T` must be set to `0`. Behavior is **undefined** if any of these bits are set to `1`.
270 #[inline(always)]
271 pub unsafe fn from_repr_unchecked(bits: <T as EnumSetTypeWithRepr>::Repr) -> Self {
272 Self { repr: bits }
273 }
274
275 /// Constructs a bitset from a `T::Repr`.
276 ///
277 /// If a bit that doesn't correspond to an enum variant is set, this
278 /// method will panic.
279 ///
280 /// In order to use this method, the definition of `T` must have an
281 /// [`#[enumset(repr = "…")]`](derive@crate::EnumSetType#representation-options) annotation
282 /// with a primitive integer type.
283 #[inline(always)]
284 pub fn from_repr(bits: <T as EnumSetTypeWithRepr>::Repr) -> Self {
285 Self::try_from_repr(bits).expect("Bitset contains invalid variants.")
286 }
287
288 /// Attempts to construct a bitset from a `T::Repr`.
289 ///
290 /// If a bit that doesn't correspond to an enum variant is set, this
291 /// method will return `None`.
292 ///
293 /// In order to use this method, the definition of `T` must have an
294 /// [`#[enumset(repr = "…")]`](derive@crate::EnumSetType#representation-options) annotation
295 /// with a primitive integer type.
296 #[inline(always)]
297 pub fn try_from_repr(bits: <T as EnumSetTypeWithRepr>::Repr) -> Option<Self> {
298 let mask = Self::all().repr;
299 if bits.and_not(mask).is_empty() {
300 Some(EnumSet { repr: bits })
301 } else {
302 None
303 }
304 }
305
306 /// Constructs a bitset from a `T::Repr`, ignoring invalid variants.
307 ///
308 /// In order to use this method, the definition of `T` must have an
309 /// [`#[enumset(repr = "…")]`](derive@crate::EnumSetType#representation-options) annotation
310 /// with a primitive integer type.
311 #[inline(always)]
312 pub fn from_repr_truncated(bits: <T as EnumSetTypeWithRepr>::Repr) -> Self {
313 let mask = Self::all().as_repr();
314 let bits = bits & mask;
315 EnumSet { repr: bits }
316 }
317}
318
319/// Helper macro for generating conversion functions.
320macro_rules! conversion_impls {
321 (
322 $(for_num!(
323 $underlying:ty, $underlying_str:expr,
324 $from_fn:ident $to_fn:ident $try_from_fn:ident $try_to_fn:ident,
325 $from:ident $try_from:ident $from_truncated:ident $from_unchecked:ident,
326 $to:ident $try_to:ident $to_truncated:ident
327 );)*
328 ) => {
329 impl<T: EnumSetType> EnumSet<T> {$(
330 #[doc = "Returns a `"]
331 #[doc = $underlying_str]
332 #[doc = "` representing the elements of this set.\n\nIf the underlying bitset will \
333 not fit in a `"]
334 #[doc = $underlying_str]
335 #[doc = "`, this method will panic."]
336 #[inline(always)]
337 pub fn $to(&self) -> $underlying {
338 self.$try_to().expect("Bitset will not fit into this type.")
339 }
340
341 #[doc = "Tries to return a `"]
342 #[doc = $underlying_str]
343 #[doc = "` representing the elements of this set.\n\nIf the underlying bitset will \
344 not fit in a `"]
345 #[doc = $underlying_str]
346 #[doc = "`, this method will return `None`."]
347 #[inline(always)]
348 pub fn $try_to(&self) -> Option<$underlying> {
349 EnumSetTypeRepr::$try_to_fn(&self.repr)
350 }
351
352 #[doc = "Returns a truncated `"]
353 #[doc = $underlying_str]
354 #[doc = "` representing the elements of this set.\n\nIf the underlying bitset will \
355 not fit in a `"]
356 #[doc = $underlying_str]
357 #[doc = "`, this method will truncate any bits that don't fit."]
358 #[inline(always)]
359 pub fn $to_truncated(&self) -> $underlying {
360 EnumSetTypeRepr::$to_fn(&self.repr)
361 }
362
363 #[doc = "Constructs 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 panic."]
367 #[inline(always)]
368 pub fn $from(bits: $underlying) -> Self {
369 Self::$try_from(bits).expect("Bitset contains invalid variants.")
370 }
371
372 #[doc = "Attempts to construct a bitset from a `"]
373 #[doc = $underlying_str]
374 #[doc = "`.\n\nIf a bit that doesn't correspond to an enum variant is set, this \
375 method will return `None`."]
376 #[inline(always)]
377 pub fn $try_from(bits: $underlying) -> Option<Self> {
378 let bits = T::Repr::$try_from_fn(bits);
379 let mask = T::ALL_BITS;
380 bits.and_then(|bits| if bits.and_not(mask).is_empty() {
381 Some(EnumSet { repr: bits })
382 } else {
383 None
384 })
385 }
386
387 #[doc = "Constructs a bitset from a `"]
388 #[doc = $underlying_str]
389 #[doc = "`, ignoring bits that do not correspond to a variant."]
390 #[inline(always)]
391 pub fn $from_truncated(bits: $underlying) -> Self {
392 let mask = Self::all().$to_truncated();
393 let bits = <T::Repr as EnumSetTypeRepr>::$from_fn(bits & mask);
394 EnumSet { repr: bits }
395 }
396
397 #[doc = "Constructs a bitset from a `"]
398 #[doc = $underlying_str]
399 #[doc = "`, without checking for invalid bits."]
400 ///
401 /// # Safety
402 ///
403 /// All bits in the provided parameter `bits` that don't correspond to an enum variant
404 /// of `T` must be set to `0`. Behavior is **undefined** if any of these bits are set
405 /// to `1`.
406 #[inline(always)]
407 pub unsafe fn $from_unchecked(bits: $underlying) -> Self {
408 EnumSet { repr: <T::Repr as EnumSetTypeRepr>::$from_fn(bits) }
409 }
410 )*}
411 }
412}
413conversion_impls! {
414 for_num!(u8, "u8",
415 from_u8 to_u8 try_from_u8 try_to_u8,
416 from_u8 try_from_u8 from_u8_truncated from_u8_unchecked,
417 as_u8 try_as_u8 as_u8_truncated);
418 for_num!(u16, "u16",
419 from_u16 to_u16 try_from_u16 try_to_u16,
420 from_u16 try_from_u16 from_u16_truncated from_u16_unchecked,
421 as_u16 try_as_u16 as_u16_truncated);
422 for_num!(u32, "u32",
423 from_u32 to_u32 try_from_u32 try_to_u32,
424 from_u32 try_from_u32 from_u32_truncated from_u32_unchecked,
425 as_u32 try_as_u32 as_u32_truncated);
426 for_num!(u64, "u64",
427 from_u64 to_u64 try_from_u64 try_to_u64,
428 from_u64 try_from_u64 from_u64_truncated from_u64_unchecked,
429 as_u64 try_as_u64 as_u64_truncated);
430 for_num!(u128, "u128",
431 from_u128 to_u128 try_from_u128 try_to_u128,
432 from_u128 try_from_u128 from_u128_truncated from_u128_unchecked,
433 as_u128 try_as_u128 as_u128_truncated);
434 for_num!(usize, "usize",
435 from_usize to_usize try_from_usize try_to_usize,
436 from_usize try_from_usize from_usize_truncated from_usize_unchecked,
437 as_usize try_as_usize as_usize_truncated);
438}
439
440impl<T: EnumSetType> EnumSet<T> {
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 panic.
444 pub fn as_array<const O: usize>(&self) -> [u64; O] {
445 self.try_as_array()
446 .expect("Bitset will not fit into this type.")
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 instead return
452 /// `None`.
453 pub fn try_as_array<const O: usize>(&self) -> Option<[u64; O]> {
454 self.repr.try_to_u64_array()
455 }
456
457 /// Returns a `[u64; O]` representing the elements of this set.
458 ///
459 /// If the underlying bitset will not fit in a `[u64; O]`, this method will truncate any bits
460 /// that don't fit.
461 pub fn as_array_truncated<const O: usize>(&self) -> [u64; O] {
462 self.repr.to_u64_array()
463 }
464
465 /// Constructs a bitset from a `[u64; O]`.
466 ///
467 /// If a bit that doesn't correspond to an enum variant is set, this method will panic.
468 pub fn from_array<const O: usize>(v: [u64; O]) -> Self {
469 Self::try_from_array(v).expect("Bitset contains invalid variants.")
470 }
471
472 /// Attempts to construct a bitset from a `[u64; O]`.
473 ///
474 /// If a bit that doesn't correspond to an enum variant is set, this method will return `None`.
475 pub fn try_from_array<const O: usize>(bits: [u64; O]) -> Option<Self> {
476 let bits = T::Repr::try_from_u64_array::<O>(bits);
477 let mask = T::ALL_BITS;
478 bits.and_then(|bits| {
479 if bits.and_not(mask).is_empty() {
480 Some(EnumSet { repr: bits })
481 } else {
482 None
483 }
484 })
485 }
486
487 /// Constructs a bitset from a `[u64; O]`, ignoring bits that do not correspond to a variant.
488 pub fn from_array_truncated<const O: usize>(bits: [u64; O]) -> Self {
489 let bits = T::Repr::from_u64_array(bits) & T::ALL_BITS;
490 EnumSet { repr: bits }
491 }
492
493 /// Constructs a bitset from a `[u64; O]`, without checking for invalid bits.
494 ///
495 /// # Safety
496 ///
497 /// All bits in the provided parameter `bits` that don't correspond to an enum variant
498 /// of `T` must be set to `0`. Behavior is **undefined** if any of these bits are set
499 /// to `1`.
500 #[inline(always)]
501 pub unsafe fn from_array_unchecked<const O: usize>(bits: [u64; O]) -> Self {
502 EnumSet { repr: T::Repr::from_u64_array(bits) }
503 }
504
505 /// Returns a `Vec<u64>` representing the elements of this set.
506 #[cfg(feature = "alloc")]
507 #[cfg_attr(docsrs, doc(cfg(feature = "alloc")))]
508 pub fn to_vec(&self) -> alloc::vec::Vec<u64> {
509 let mut vec = alloc::vec![0; T::Repr::PREFERRED_ARRAY_LEN];
510 self.repr.to_u64_slice(&mut vec);
511 vec
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 panic.
517 pub fn copy_into_slice(&self, data: &mut [u64]) {
518 self.try_copy_into_slice(data)
519 .expect("Bitset will not fit into slice.")
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 return
525 /// `None`. Otherwise, it will return `Some(())`.
526 #[must_use]
527 pub fn try_copy_into_slice(&self, data: &mut [u64]) -> Option<()> {
528 self.repr.try_to_u64_slice(data)
529 }
530
531 /// Copies the elements of this set into a `&mut [u64]`.
532 ///
533 /// If the underlying bitset will not fit in the provided slice, this method will truncate any
534 /// bits that don't fit.
535 pub fn copy_into_slice_truncated(&self, data: &mut [u64]) {
536 self.repr.to_u64_slice(data)
537 }
538
539 /// Constructs a bitset from a `&[u64]`.
540 ///
541 /// If a bit that doesn't correspond to an enum variant is set, this method will panic.
542 pub fn from_slice(v: &[u64]) -> Self {
543 Self::try_from_slice(v).expect("Bitset contains invalid variants.")
544 }
545
546 /// Attempts to construct a bitset from a `&[u64]`.
547 ///
548 /// If a bit that doesn't correspond to an enum variant is set, this method will return `None`.
549 pub fn try_from_slice(bits: &[u64]) -> Option<Self> {
550 let bits = T::Repr::try_from_u64_slice(bits);
551 let mask = T::ALL_BITS;
552 bits.and_then(|bits| {
553 if bits.and_not(mask).is_empty() {
554 Some(EnumSet { repr: bits })
555 } else {
556 None
557 }
558 })
559 }
560
561 /// Constructs a bitset from a `&[u64]`, ignoring bits that do not correspond to a variant.
562 pub fn from_slice_truncated(bits: &[u64]) -> Self {
563 let bits = T::Repr::from_u64_slice(bits) & T::ALL_BITS;
564 EnumSet { repr: bits }
565 }
566
567 /// Constructs a bitset from a `&[u64]`, without checking for invalid bits.
568 ///
569 /// # Safety
570 ///
571 /// All bits in the provided parameter `bits` that don't correspond to an enum variant
572 /// of `T` must be set to `0`. Behavior is **undefined** if any of these bits are set
573 /// to `1`.
574 #[inline(always)]
575 pub unsafe fn from_slice_unchecked(bits: &[u64]) -> Self {
576 EnumSet { repr: T::Repr::from_u64_slice(bits) }
577 }
578}
579
580impl<T: EnumSetType, const N: usize> From<[T; N]> for EnumSet<T> {
581 fn from(value: [T; N]) -> Self {
582 let mut new = EnumSet::new();
583 for elem in value {
584 new.insert(elem);
585 }
586 new
587 }
588}
589//endregion
590
591//region EnumSet iter
592/// The iterator used by [`EnumSet`]s.
593#[derive(Clone, Debug)]
594pub struct EnumSetIter<T: EnumSetType> {
595 iter: <T::Repr as EnumSetTypeRepr>::Iter,
596}
597impl<T: EnumSetType> EnumSetIter<T> {
598 fn new(set: EnumSet<T>) -> EnumSetIter<T> {
599 EnumSetIter { iter: set.repr.iter() }
600 }
601}
602
603impl<T: EnumSetType> EnumSet<T> {
604 /// Iterates the contents of the set in order from the least significant bit to the most
605 /// significant bit.
606 ///
607 /// Note that iterator invalidation is impossible as the iterator contains a copy of this type,
608 /// rather than holding a reference to it.
609 pub fn iter(&self) -> EnumSetIter<T> {
610 EnumSetIter::new(*self)
611 }
612}
613
614impl<T: EnumSetType> Iterator for EnumSetIter<T> {
615 type Item = T;
616
617 fn next(&mut self) -> Option<Self::Item> {
618 self.iter
619 .next()
620 .map(|x| unsafe { T::enum_from_u32_checked(x) })
621 }
622 fn size_hint(&self) -> (usize, Option<usize>) {
623 self.iter.size_hint()
624 }
625}
626impl<T: EnumSetType> DoubleEndedIterator for EnumSetIter<T> {
627 fn next_back(&mut self) -> Option<Self::Item> {
628 self.iter
629 .next_back()
630 .map(|x| unsafe { T::enum_from_u32_checked(x) })
631 }
632}
633impl<T: EnumSetType> ExactSizeIterator for EnumSetIter<T> {}
634
635set_iterator_impls!(EnumSet, EnumSetType);
636
637impl<T: EnumSetType> IntoIterator for EnumSet<T> {
638 type Item = T;
639 type IntoIter = EnumSetIter<T>;
640
641 fn into_iter(self) -> Self::IntoIter {
642 self.iter()
643 }
644}
645//endregion