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