]> git.lizzy.rs Git - enumset.git/blob - enumset/src/lib.rs
Split repr into its own module.
[enumset.git] / enumset / src / lib.rs
1 #![no_std]
2 #![forbid(missing_docs)]
3
4 //! A library for defining enums that can be used in compact bit sets. It supports enums up to 128
5 //! variants, and has a macro to use these sets in constants.
6 //!
7 //! For serde support, enable the `serde` feature.
8 //!
9 //! # Defining enums for use with EnumSet
10 //!
11 //! Enums to be used with [`EnumSet`] should be defined using `#[derive(EnumSetType)]`:
12 //!
13 //! ```rust
14 //! # use enumset::*;
15 //! #[derive(EnumSetType, Debug)]
16 //! pub enum Enum {
17 //!    A, B, C, D, E, F, G,
18 //! }
19 //! ```
20 //!
21 //! For more information on more advanced use cases, see the documentation for [`EnumSetType`].
22 //!
23 //! # Working with EnumSets
24 //!
25 //! EnumSets can be constructed via [`EnumSet::new()`] like a normal set. In addition,
26 //! `#[derive(EnumSetType)]` creates operator overloads that allow you to create EnumSets like so:
27 //!
28 //! ```rust
29 //! # use enumset::*;
30 //! # #[derive(EnumSetType, Debug)] pub enum Enum { A, B, C, D, E, F, G }
31 //! let new_set = Enum::A | Enum::C | Enum::G;
32 //! assert_eq!(new_set.len(), 3);
33 //! ```
34 //!
35 //! All bitwise operations you would expect to work on bitsets also work on both EnumSets and
36 //! enums with `#[derive(EnumSetType)]`:
37 //! ```rust
38 //! # use enumset::*;
39 //! # #[derive(EnumSetType, Debug)] pub enum Enum { A, B, C, D, E, F, G }
40 //! // Intersection of sets
41 //! assert_eq!((Enum::A | Enum::B) & Enum::C, EnumSet::empty());
42 //! assert_eq!((Enum::A | Enum::B) & Enum::A, Enum::A);
43 //! assert_eq!(Enum::A & Enum::B, EnumSet::empty());
44 //!
45 //! // Symmetric difference of sets
46 //! assert_eq!((Enum::A | Enum::B) ^ (Enum::B | Enum::C), Enum::A | Enum::C);
47 //! assert_eq!(Enum::A ^ Enum::C, Enum::A | Enum::C);
48 //!
49 //! // Difference of sets
50 //! assert_eq!((Enum::A | Enum::B | Enum::C) - Enum::B, Enum::A | Enum::C);
51 //!
52 //! // Complement of sets
53 //! assert_eq!(!(Enum::E | Enum::G), Enum::A | Enum::B | Enum::C | Enum::D | Enum::F);
54 //! ```
55 //!
56 //! The [`enum_set!`] macro allows you to create EnumSets in constant contexts:
57 //!
58 //! ```rust
59 //! # use enumset::*;
60 //! # #[derive(EnumSetType, Debug)] pub enum Enum { A, B, C, D, E, F, G }
61 //! const CONST_SET: EnumSet<Enum> = enum_set!(Enum::A | Enum::B);
62 //! assert_eq!(CONST_SET, Enum::A | Enum::B);
63 //! ```
64 //!
65 //! Mutable operations on the [`EnumSet`] otherwise similarly to Rust's builtin sets:
66 //!
67 //! ```rust
68 //! # use enumset::*;
69 //! # #[derive(EnumSetType, Debug)] pub enum Enum { A, B, C, D, E, F, G }
70 //! let mut set = EnumSet::new();
71 //! set.insert(Enum::A);
72 //! set.insert_all(Enum::E | Enum::G);
73 //! assert!(set.contains(Enum::A));
74 //! assert!(!set.contains(Enum::B));
75 //! assert_eq!(set, Enum::A | Enum::E | Enum::G);
76 //! ```
77
78 pub use enumset_derive::EnumSetType;
79
80 use core::cmp::Ordering;
81 use core::fmt;
82 use core::fmt::{Debug, Formatter};
83 use core::hash::{Hash, Hasher};
84 use core::iter::FromIterator;
85 use core::ops::*;
86
87 #[doc(hidden)]
88 /// Everything in this module is internal API and may change at any time.
89 pub mod __internal {
90     use super::*;
91
92     /// A reexport of core to allow our macros to be generic to std vs core.
93     pub use ::core as core_export;
94
95     /// A reexport of serde so there is no requirement to depend on serde.
96     #[cfg(feature = "serde")] pub use serde2 as serde;
97
98     /// The actual members of EnumSetType. Put here to avoid polluting global namespaces.
99     pub unsafe trait EnumSetTypePrivate {
100         /// The underlying type used to store the bitset.
101         type Repr: EnumSetTypeRepr;
102         /// A mask of bits that are valid in the bitset.
103         const ALL_BITS: Self::Repr;
104
105         /// Converts an enum of this type into its bit position.
106         fn enum_into_u32(self) -> u32;
107         /// Converts a bit position into an enum value.
108         unsafe fn enum_from_u32(val: u32) -> Self;
109
110         /// Serializes the `EnumSet`.
111         ///
112         /// This and `deserialize` are part of the `EnumSetType` trait so the procedural derive
113         /// can control how `EnumSet` is serialized.
114         #[cfg(feature = "serde")]
115         fn serialize<S: serde::Serializer>(set: EnumSet<Self>, ser: S) -> Result<S::Ok, S::Error>
116             where Self: EnumSetType;
117         /// Deserializes the `EnumSet`.
118         #[cfg(feature = "serde")]
119         fn deserialize<'de, D: serde::Deserializer<'de>>(de: D) -> Result<EnumSet<Self>, D::Error>
120             where Self: EnumSetType;
121     }
122 }
123 use crate::__internal::EnumSetTypePrivate;
124 #[cfg(feature = "serde")] use crate::__internal::serde;
125 #[cfg(feature = "serde")] use crate::serde::{Serialize, Deserialize};
126
127 mod repr;
128 use crate::repr::EnumSetTypeRepr;
129
130 /// The trait used to define enum types that may be used with [`EnumSet`].
131 ///
132 /// This trait should be implemented using `#[derive(EnumSetType)]`. Its internal structure is
133 /// not stable, and may change at any time.
134 ///
135 /// # Custom Derive
136 ///
137 /// Any C-like enum is supported, as long as there are no more than 128 variants in the enum,
138 /// and no variant discriminator is larger than 127.
139 ///
140 /// The custom derive for [`EnumSetType`] automatically creates implementations of [`PartialEq`],
141 /// [`Sub`], [`BitAnd`], [`BitOr`], [`BitXor`], and [`Not`] allowing the enum to be used as
142 /// if it were an [`EnumSet`] in expressions. This can be disabled by adding an `#[enumset(no_ops)]`
143 /// annotation to the enum.
144 ///
145 /// The custom derive for `EnumSetType` automatically implements [`Copy`], [`Clone`], [`Eq`], and
146 /// [`PartialEq`] on the enum. These are required for the [`EnumSet`] to function.
147 ///
148 /// In addition, if you have renamed the `enumset` crate in your crate, you can use the
149 /// `#[enumset(crate_name = "enumset2")]` attribute to tell the custom derive to use that name
150 /// instead.
151 ///
152 /// Attributes controlling the serialization of an `EnumSet` are documented in
153 /// [its documentation](./struct.EnumSet.html#serialization).
154 ///
155 /// # Examples
156 ///
157 /// Deriving a plain EnumSetType:
158 ///
159 /// ```rust
160 /// # use enumset::*;
161 /// #[derive(EnumSetType)]
162 /// pub enum Enum {
163 ///    A, B, C, D, E, F, G,
164 /// }
165 /// ```
166 ///
167 /// Deriving a sparse EnumSetType:
168 ///
169 /// ```rust
170 /// # use enumset::*;
171 /// #[derive(EnumSetType)]
172 /// pub enum SparseEnum {
173 ///    A = 10, B = 20, C = 30, D = 127,
174 /// }
175 /// ```
176 ///
177 /// Deriving an EnumSetType without adding ops:
178 ///
179 /// ```rust
180 /// # use enumset::*;
181 /// #[derive(EnumSetType)]
182 /// #[enumset(no_ops)]
183 /// pub enum NoOpsEnum {
184 ///    A, B, C, D, E, F, G,
185 /// }
186 /// ```
187 pub unsafe trait EnumSetType: Copy + Eq + EnumSetTypePrivate { }
188
189 /// An efficient set type for enums.
190 ///
191 /// It is implemented using a bitset stored using the smallest integer that can fit all bits
192 /// in the underlying enum. In general, an enum variant with a numeric value of `n` is stored in
193 /// the nth least significant bit (corresponding with a mask of, e.g. `1 << enum as u32`).
194 ///
195 /// # Serialization
196 ///
197 /// When the `serde` feature is enabled, `EnumSet`s can be serialized and deserialized using
198 /// the `serde` crate. The exact serialization format can be controlled with additional attributes
199 /// on the enum type. These attributes are valid regardless of whether the `serde` feature
200 /// is enabled.
201 ///
202 /// By default, `EnumSet`s serialize by directly writing out the underlying bitset as an integer
203 /// of the smallest type that can fit in the underlying enum. You can add a
204 /// `#[enumset(serialize_repr = "u8")]` attribute to your enum to control the integer type used
205 /// for serialization. This can be important for avoiding unintentional breaking changes when
206 /// `EnumSet`s are serialized with formats like `bincode`.
207 ///
208 /// By default, unknown bits are ignored and silently removed from the bitset. To override this
209 /// behavior, you can add a `#[enumset(serialize_deny_unknown)]` attribute. This will cause
210 /// deserialization to fail if an invalid bit is set.
211 ///
212 /// In addition, the `#[enumset(serialize_as_list)]` attribute causes the `EnumSet` to be
213 /// instead serialized as a list of enum variants. This requires your enum type implement
214 /// [`Serialize`] and [`Deserialize`]. Note that this is a breaking change
215 #[derive(Copy, Clone, PartialEq, Eq)]
216 pub struct EnumSet<T: EnumSetType> {
217     #[doc(hidden)]
218     /// This is public due to the [`enum_set!`] macro.
219     /// This is **NOT** public API and may change at any time.
220     pub __priv_repr: T::Repr
221 }
222 impl <T: EnumSetType> EnumSet<T> {
223     // Returns all bits valid for the enum
224     fn all_bits() -> T::Repr {
225         T::ALL_BITS
226     }
227
228     /// Creates an empty `EnumSet`.
229     pub fn new() -> Self {
230         EnumSet { __priv_repr: T::Repr::empty() }
231     }
232
233     /// Returns an `EnumSet` containing a single element.
234     pub fn only(t: T) -> Self {
235         let mut set = Self::new();
236         set.insert(t);
237         set
238     }
239
240     /// Creates an empty `EnumSet`.
241     ///
242     /// This is an alias for [`EnumSet::new`].
243     pub fn empty() -> Self {
244         Self::new()
245     }
246
247     /// Returns an `EnumSet` containing all valid variants of the enum.
248     pub fn all() -> Self {
249         EnumSet { __priv_repr: Self::all_bits() }
250     }
251
252     /// Total number of bits used by this type. Note that the actual amount of space used is
253     /// rounded up to the next highest integer type (`u8`, `u16`, `u32`, `u64`, or `u128`).
254     ///
255     /// This is the same as [`EnumSet::variant_count`] except in enums with "sparse" variants.
256     /// (e.g. `enum Foo { A = 10, B = 20 }`)
257     pub fn bit_width() -> u32 {
258         T::Repr::WIDTH - T::ALL_BITS.leading_zeros()
259     }
260
261     /// The number of valid variants that this type can contain.
262     ///
263     /// This is the same as [`EnumSet::bit_width`] except in enums with "sparse" variants.
264     /// (e.g. `enum Foo { A = 10, B = 20 }`)
265     pub fn variant_count() -> u32 {
266         T::ALL_BITS.count_ones()
267     }
268
269     /// Returns the number of elements in this set.
270     pub fn len(&self) -> usize {
271         self.__priv_repr.count_ones() as usize
272     }
273     /// Returns `true` if the set contains no elements.
274     pub fn is_empty(&self) -> bool {
275         self.__priv_repr.is_empty()
276     }
277     /// Removes all elements from the set.
278     pub fn clear(&mut self) {
279         self.__priv_repr = T::Repr::empty()
280     }
281
282     /// Returns `true` if `self` has no elements in common with `other`. This is equivalent to
283     /// checking for an empty intersection.
284     pub fn is_disjoint(&self, other: Self) -> bool {
285         (*self & other).is_empty()
286     }
287     /// Returns `true` if the set is a superset of another, i.e., `self` contains at least all the
288     /// values in `other`.
289     pub fn is_superset(&self, other: Self) -> bool {
290         (*self & other).__priv_repr == other.__priv_repr
291     }
292     /// Returns `true` if the set is a subset of another, i.e., `other` contains at least all
293     /// the values in `self`.
294     pub fn is_subset(&self, other: Self) -> bool {
295         other.is_superset(*self)
296     }
297
298     /// Returns a set containing any elements present in either set.
299     pub fn union(&self, other: Self) -> Self {
300         EnumSet { __priv_repr: self.__priv_repr | other.__priv_repr }
301     }
302     /// Returns a set containing every element present in both sets.
303     pub fn intersection(&self, other: Self) -> Self {
304         EnumSet { __priv_repr: self.__priv_repr & other.__priv_repr }
305     }
306     /// Returns a set containing element present in `self` but not in `other`.
307     pub fn difference(&self, other: Self) -> Self {
308         EnumSet { __priv_repr: self.__priv_repr.and_not(other.__priv_repr) }
309     }
310     /// Returns a set containing every element present in either `self` or `other`, but is not
311     /// present in both.
312     pub fn symmetrical_difference(&self, other: Self) -> Self {
313         EnumSet { __priv_repr: self.__priv_repr ^ other.__priv_repr }
314     }
315     /// Returns a set containing all enum variants not in this set.
316     pub fn complement(&self) -> Self {
317         EnumSet { __priv_repr: !self.__priv_repr & Self::all_bits() }
318     }
319
320     /// Checks whether this set contains a value.
321     pub fn contains(&self, value: T) -> bool {
322         self.__priv_repr.has_bit(value.enum_into_u32())
323     }
324
325     /// Adds a value to this set.
326     ///
327     /// If the set did not have this value present, `true` is returned.
328     ///
329     /// If the set did have this value present, `false` is returned.
330     pub fn insert(&mut self, value: T) -> bool {
331         let contains = !self.contains(value);
332         self.__priv_repr.add_bit(value.enum_into_u32());
333         contains
334     }
335     /// Removes a value from this set. Returns whether the value was present in the set.
336     pub fn remove(&mut self, value: T) -> bool {
337         let contains = self.contains(value);
338         self.__priv_repr.remove_bit(value.enum_into_u32());
339         contains
340     }
341
342     /// Adds all elements in another set to this one.
343     pub fn insert_all(&mut self, other: Self) {
344         self.__priv_repr = self.__priv_repr | other.__priv_repr
345     }
346     /// Removes all values in another set from this one.
347     pub fn remove_all(&mut self, other: Self) {
348         self.__priv_repr = self.__priv_repr.and_not(other.__priv_repr);
349     }
350
351     /// Creates an iterator over the values in this set.
352     ///
353     /// Note that iterator invalidation is impossible as the iterator contains a copy of this type,
354     /// rather than holding a reference to it.
355     pub fn iter(&self) -> EnumSetIter<T> {
356         EnumSetIter(*self, 0)
357     }
358 }
359
360 /// Helper macro for generating conversion functions.
361 macro_rules! conversion_impls {
362     (
363         $(for_num!(
364             $underlying:ty, $underlying_str:expr,
365             $from_fn:ident $to_fn:ident $from_fn_opt:ident $to_fn_opt:ident,
366             $from:ident $try_from:ident $from_truncated:ident
367             $to:ident $try_to:ident $to_truncated:ident
368         );)*
369     ) => {
370         impl <T : EnumSetType> EnumSet<T> {$(
371             #[doc = "Returns a `"]
372             #[doc = $underlying_str]
373             #[doc = "` representing the elements of this set.\n\nIf the underlying bitset will \
374                      not fit in a `"]
375             #[doc = $underlying_str]
376             #[doc = "`, this method will panic."]
377             pub fn $to(&self) -> $underlying {
378                 self.$try_to().expect("Bitset will not fit into this type.")
379             }
380
381             #[doc = "Tries to return a `"]
382             #[doc = $underlying_str]
383             #[doc = "` representing the elements of this set.\n\nIf the underlying bitset will \
384                      not fit in a `"]
385             #[doc = $underlying_str]
386             #[doc = "`, this method will instead return `None`."]
387             pub fn $try_to(&self) -> Option<$underlying> {
388                 EnumSetTypeRepr::$to_fn_opt(&self.__priv_repr)
389             }
390
391             #[doc = "Returns a truncated `"]
392             #[doc = $underlying_str]
393             #[doc = "` representing the elements of this set.\n\nIf the underlying bitset will \
394                      not fit in a `"]
395             #[doc = $underlying_str]
396             #[doc = "`, this method will truncate any bits that don't fit."]
397             pub fn $to_truncated(&self) -> $underlying {
398                 EnumSetTypeRepr::$to_fn(&self.__priv_repr)
399             }
400
401             #[doc = "Constructs a bitset from a `"]
402             #[doc = $underlying_str]
403             #[doc = "`.\n\nIf a bit that doesn't correspond to an enum variant is set, this \
404                      method will panic."]
405             pub fn $from(bits: $underlying) -> Self {
406                 Self::$try_from(bits).expect("Bitset contains invalid variants.")
407             }
408
409             #[doc = "Attempts to constructs a bitset from a `"]
410             #[doc = $underlying_str]
411             #[doc = "`.\n\nIf a bit that doesn't correspond to an enum variant is set, this \
412                      method will return `None`."]
413             pub fn $try_from(bits: $underlying) -> Option<Self> {
414                 let bits = T::Repr::$from_fn_opt(bits);
415                 let mask = Self::all().__priv_repr;
416                 bits.and_then(|bits| if bits.and_not(mask).is_empty() {
417                     Some(EnumSet { __priv_repr: bits })
418                 } else {
419                     None
420                 })
421             }
422
423             #[doc = "Constructs a bitset from a `"]
424             #[doc = $underlying_str]
425             #[doc = "`, ignoring invalid variants."]
426             pub fn $from_truncated(bits: $underlying) -> Self {
427                 let mask = Self::all().$to_truncated();
428                 let bits = <T::Repr as EnumSetTypeRepr>::$from_fn(bits & mask);
429                 EnumSet { __priv_repr: bits }
430             }
431         )*}
432     }
433 }
434 conversion_impls! {
435     for_num!(u8, "u8", from_u8 to_u8 from_u8_opt to_u8_opt,
436              from_u8 try_from_u8 from_u8_truncated as_u8 try_as_u8 as_u8_truncated);
437     for_num!(u16, "u16", from_u16 to_u16 from_u16_opt to_u16_opt,
438              from_u16 try_from_u16 from_u16_truncated as_u16 try_as_u16 as_u16_truncated);
439     for_num!(u32, "u32", from_u32 to_u32 from_u32_opt to_u32_opt,
440              from_u32 try_from_u32 from_u32_truncated as_u32 try_as_u32 as_u32_truncated);
441     for_num!(u64, "u64", from_u64 to_u64 from_u64_opt to_u64_opt,
442              from_u64 try_from_u64 from_u64_truncated as_u64 try_as_u64 as_u64_truncated);
443     for_num!(u128, "u128", from_u128 to_u128 from_u128_opt to_u128_opt,
444              from_u128 try_from_u128 from_u128_truncated as_u128 try_as_u128 as_u128_truncated);
445     for_num!(usize, "usize", from_usize to_usize from_usize_opt to_usize_opt,
446              from_usize try_from_usize from_usize_truncated
447              as_usize try_as_usize as_usize_truncated);
448 }
449
450 impl <T: EnumSetType> Default for EnumSet<T> {
451     /// Returns an empty set.
452     fn default() -> Self {
453         Self::new()
454     }
455 }
456
457 impl <T: EnumSetType> IntoIterator for EnumSet<T> {
458     type Item = T;
459     type IntoIter = EnumSetIter<T>;
460
461     fn into_iter(self) -> Self::IntoIter {
462         self.iter()
463     }
464 }
465
466 impl <T: EnumSetType, O: Into<EnumSet<T>>> Sub<O> for EnumSet<T> {
467     type Output = Self;
468     fn sub(self, other: O) -> Self::Output {
469         self.difference(other.into())
470     }
471 }
472 impl <T: EnumSetType, O: Into<EnumSet<T>>> BitAnd<O> for EnumSet<T> {
473     type Output = Self;
474     fn bitand(self, other: O) -> Self::Output {
475         self.intersection(other.into())
476     }
477 }
478 impl <T: EnumSetType, O: Into<EnumSet<T>>> BitOr<O> for EnumSet<T> {
479     type Output = Self;
480     fn bitor(self, other: O) -> Self::Output {
481         self.union(other.into())
482     }
483 }
484 impl <T: EnumSetType, O: Into<EnumSet<T>>> BitXor<O> for EnumSet<T> {
485     type Output = Self;
486     fn bitxor(self, other: O) -> Self::Output {
487         self.symmetrical_difference(other.into())
488     }
489 }
490
491 impl <T: EnumSetType, O: Into<EnumSet<T>>> SubAssign<O> for EnumSet<T> {
492     fn sub_assign(&mut self, rhs: O) {
493         *self = *self - rhs;
494     }
495 }
496 impl <T: EnumSetType, O: Into<EnumSet<T>>> BitAndAssign<O> for EnumSet<T> {
497     fn bitand_assign(&mut self, rhs: O) {
498         *self = *self & rhs;
499     }
500 }
501 impl <T: EnumSetType, O: Into<EnumSet<T>>> BitOrAssign<O> for EnumSet<T> {
502     fn bitor_assign(&mut self, rhs: O) {
503         *self = *self | rhs;
504     }
505 }
506 impl <T: EnumSetType, O: Into<EnumSet<T>>> BitXorAssign<O> for EnumSet<T> {
507     fn bitxor_assign(&mut self, rhs: O) {
508         *self = *self ^ rhs;
509     }
510 }
511
512 impl <T: EnumSetType> Not for EnumSet<T> {
513     type Output = Self;
514     fn not(self) -> Self::Output {
515         self.complement()
516     }
517 }
518
519 impl <T: EnumSetType> From<T> for EnumSet<T> {
520     fn from(t: T) -> Self {
521         EnumSet::only(t)
522     }
523 }
524
525 impl <T: EnumSetType> PartialEq<T> for EnumSet<T> {
526     fn eq(&self, other: &T) -> bool {
527         self.__priv_repr == EnumSet::only(*other).__priv_repr
528     }
529 }
530 impl <T: EnumSetType + Debug> Debug for EnumSet<T> {
531     fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
532         let mut is_first = true;
533         f.write_str("EnumSet(")?;
534         for v in self.iter() {
535             if !is_first { f.write_str(" | ")?; }
536             is_first = false;
537             v.fmt(f)?;
538         }
539         f.write_str(")")?;
540         Ok(())
541     }
542 }
543
544 impl <T: EnumSetType> Hash for EnumSet<T> {
545     fn hash<H: Hasher>(&self, state: &mut H) {
546         self.__priv_repr.hash(state)
547     }
548 }
549 impl <T: EnumSetType> PartialOrd for EnumSet<T> {
550     fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
551         self.__priv_repr.partial_cmp(&other.__priv_repr)
552     }
553 }
554 impl <T: EnumSetType> Ord for EnumSet<T> {
555     fn cmp(&self, other: &Self) -> Ordering {
556         self.__priv_repr.cmp(&other.__priv_repr)
557     }
558 }
559
560 #[cfg(feature = "serde")]
561 impl <T: EnumSetType> Serialize for EnumSet<T> {
562     fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
563         T::serialize(*self, serializer)
564     }
565 }
566
567 #[cfg(feature = "serde")]
568 impl <'de, T: EnumSetType> Deserialize<'de> for EnumSet<T> {
569     fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
570         T::deserialize(deserializer)
571     }
572 }
573
574 /// The iterator used by [`EnumSet`]s.
575 #[derive(Clone, Debug)]
576 pub struct EnumSetIter<T: EnumSetType>(EnumSet<T>, u32);
577 impl <T: EnumSetType> Iterator for EnumSetIter<T> {
578     type Item = T;
579
580     fn next(&mut self) -> Option<Self::Item> {
581         while self.1 < EnumSet::<T>::bit_width() {
582             let bit = self.1;
583             self.1 += 1;
584             if self.0.__priv_repr.has_bit(bit) {
585                 return unsafe { Some(T::enum_from_u32(bit)) }
586             }
587         }
588         None
589     }
590     fn size_hint(&self) -> (usize, Option<usize>) {
591         let left = self.0.__priv_repr.count_remaining_ones(self.1);
592         (left, Some(left))
593     }
594 }
595
596 impl<T: EnumSetType> Extend<T> for EnumSet<T> {
597     fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I) {
598         iter.into_iter().for_each(|v| { self.insert(v); });
599     }
600 }
601
602 impl<T: EnumSetType> FromIterator<T> for EnumSet<T> {
603     fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self {
604         let mut set = EnumSet::default();
605         set.extend(iter);
606         set
607     }
608 }
609
610 impl<T: EnumSetType> Extend<EnumSet<T>> for EnumSet<T> {
611     fn extend<I: IntoIterator<Item = EnumSet<T>>>(&mut self, iter: I) {
612         iter.into_iter().for_each(|v| { self.insert_all(v); });
613     }
614 }
615
616 impl<T: EnumSetType> FromIterator<EnumSet<T>> for EnumSet<T> {
617     fn from_iter<I: IntoIterator<Item = EnumSet<T>>>(iter: I) -> Self {
618         let mut set = EnumSet::default();
619         set.extend(iter);
620         set
621     }
622 }
623
624 /// Creates a EnumSet literal, which can be used in const contexts.
625 ///
626 /// The syntax used is `enum_set!(Type::A | Type::B | Type::C)`. Each variant must be of the same
627 /// type, or a error will occur at compile-time.
628 ///
629 /// This macro accepts trailing `|`s to allow easier use in other macros.
630 ///
631 /// # Examples
632 ///
633 /// ```rust
634 /// # use enumset::*;
635 /// # #[derive(EnumSetType, Debug)] enum Enum { A, B, C }
636 /// const CONST_SET: EnumSet<Enum> = enum_set!(Enum::A | Enum::B);
637 /// assert_eq!(CONST_SET, Enum::A | Enum::B);
638 /// ```
639 ///
640 /// This macro is strongly typed. For example, the following will not compile:
641 ///
642 /// ```compile_fail
643 /// # use enumset::*;
644 /// # #[derive(EnumSetType, Debug)] enum Enum { A, B, C }
645 /// # #[derive(EnumSetType, Debug)] enum Enum2 { A, B, C }
646 /// let type_error = enum_set!(Enum::A | Enum2::B);
647 /// ```
648 #[macro_export]
649 macro_rules! enum_set {
650     ($(|)*) => {
651         $crate::EnumSet { __priv_repr: 0 }
652     };
653     ($value:path $(|)*) => {
654         $value.__impl_enumset_internal__const_only()
655     };
656     ($value:path | $($rest:path)|* $(|)*) => {
657         {
658             #[allow(deprecated)] let value = $value.__impl_enumset_internal__const_only();
659             $(#[allow(deprecated)] let value = $rest.__impl_enumset_internal__const_merge(value);)*
660             value
661         }
662     };
663 }