]> git.lizzy.rs Git - enumset.git/blob - enumset/src/lib.rs
98c7977688f6c1b4af9d06b68b0eee7b04503c5a
[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, Sum};
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 #[repr(transparent)]
217 pub struct EnumSet<T: EnumSetType> {
218     #[doc(hidden)]
219     /// This is public due to the [`enum_set!`] macro.
220     /// This is **NOT** public API and may change at any time.
221     pub __priv_repr: T::Repr
222 }
223 impl <T: EnumSetType> EnumSet<T> {
224     // Returns all bits valid for the enum
225     fn all_bits() -> T::Repr {
226         T::ALL_BITS
227     }
228
229     /// Creates an empty `EnumSet`.
230     pub fn new() -> Self {
231         EnumSet { __priv_repr: T::Repr::empty() }
232     }
233
234     /// Returns an `EnumSet` containing a single element.
235     pub fn only(t: T) -> Self {
236         let mut set = Self::new();
237         set.insert(t);
238         set
239     }
240
241     /// Creates an empty `EnumSet`.
242     ///
243     /// This is an alias for [`EnumSet::new`].
244     pub fn empty() -> Self {
245         Self::new()
246     }
247
248     /// Returns an `EnumSet` containing all valid variants of the enum.
249     pub fn all() -> Self {
250         EnumSet { __priv_repr: Self::all_bits() }
251     }
252
253     /// Total number of bits used by this type. Note that the actual amount of space used is
254     /// rounded up to the next highest integer type (`u8`, `u16`, `u32`, `u64`, or `u128`).
255     ///
256     /// This is the same as [`EnumSet::variant_count`] except in enums with "sparse" variants.
257     /// (e.g. `enum Foo { A = 10, B = 20 }`)
258     pub fn bit_width() -> u32 {
259         T::Repr::WIDTH - T::ALL_BITS.leading_zeros()
260     }
261
262     /// The number of valid variants that this type can contain.
263     ///
264     /// This is the same as [`EnumSet::bit_width`] except in enums with "sparse" variants.
265     /// (e.g. `enum Foo { A = 10, B = 20 }`)
266     pub fn variant_count() -> u32 {
267         T::ALL_BITS.count_ones()
268     }
269
270     /// Returns the number of elements in this set.
271     pub fn len(&self) -> usize {
272         self.__priv_repr.count_ones() as usize
273     }
274     /// Returns `true` if the set contains no elements.
275     pub fn is_empty(&self) -> bool {
276         self.__priv_repr.is_empty()
277     }
278     /// Removes all elements from the set.
279     pub fn clear(&mut self) {
280         self.__priv_repr = T::Repr::empty()
281     }
282
283     /// Returns `true` if `self` has no elements in common with `other`. This is equivalent to
284     /// checking for an empty intersection.
285     pub fn is_disjoint(&self, other: Self) -> bool {
286         (*self & other).is_empty()
287     }
288     /// Returns `true` if the set is a superset of another, i.e., `self` contains at least all the
289     /// values in `other`.
290     pub fn is_superset(&self, other: Self) -> bool {
291         (*self & other).__priv_repr == other.__priv_repr
292     }
293     /// Returns `true` if the set is a subset of another, i.e., `other` contains at least all
294     /// the values in `self`.
295     pub fn is_subset(&self, other: Self) -> bool {
296         other.is_superset(*self)
297     }
298
299     /// Returns a set containing any elements present in either set.
300     pub fn union(&self, other: Self) -> Self {
301         EnumSet { __priv_repr: self.__priv_repr | other.__priv_repr }
302     }
303     /// Returns a set containing every element present in both sets.
304     pub fn intersection(&self, other: Self) -> Self {
305         EnumSet { __priv_repr: self.__priv_repr & other.__priv_repr }
306     }
307     /// Returns a set containing element present in `self` but not in `other`.
308     pub fn difference(&self, other: Self) -> Self {
309         EnumSet { __priv_repr: self.__priv_repr.and_not(other.__priv_repr) }
310     }
311     /// Returns a set containing every element present in either `self` or `other`, but is not
312     /// present in both.
313     pub fn symmetrical_difference(&self, other: Self) -> Self {
314         EnumSet { __priv_repr: self.__priv_repr ^ other.__priv_repr }
315     }
316     /// Returns a set containing all enum variants not in this set.
317     pub fn complement(&self) -> Self {
318         EnumSet { __priv_repr: !self.__priv_repr & Self::all_bits() }
319     }
320
321     /// Checks whether this set contains a value.
322     pub fn contains(&self, value: T) -> bool {
323         self.__priv_repr.has_bit(value.enum_into_u32())
324     }
325
326     /// Adds a value to this set.
327     ///
328     /// If the set did not have this value present, `true` is returned.
329     ///
330     /// If the set did have this value present, `false` is returned.
331     pub fn insert(&mut self, value: T) -> bool {
332         let contains = !self.contains(value);
333         self.__priv_repr.add_bit(value.enum_into_u32());
334         contains
335     }
336     /// Removes a value from this set. Returns whether the value was present in the set.
337     pub fn remove(&mut self, value: T) -> bool {
338         let contains = self.contains(value);
339         self.__priv_repr.remove_bit(value.enum_into_u32());
340         contains
341     }
342
343     /// Adds all elements in another set to this one.
344     pub fn insert_all(&mut self, other: Self) {
345         self.__priv_repr = self.__priv_repr | other.__priv_repr
346     }
347     /// Removes all values in another set from this one.
348     pub fn remove_all(&mut self, other: Self) {
349         self.__priv_repr = self.__priv_repr.and_not(other.__priv_repr);
350     }
351
352     /// Creates an iterator over the values in this set.
353     ///
354     /// Note that iterator invalidation is impossible as the iterator contains a copy of this type,
355     /// rather than holding a reference to it.
356     pub fn iter(&self) -> EnumSetIter<T> {
357         EnumSetIter(*self)
358     }
359 }
360
361 /// Helper macro for generating conversion functions.
362 macro_rules! conversion_impls {
363     (
364         $(for_num!(
365             $underlying:ty, $underlying_str:expr,
366             $from_fn:ident $to_fn:ident $from_fn_opt:ident $to_fn_opt:ident,
367             $from:ident $try_from:ident $from_truncated:ident
368             $to:ident $try_to:ident $to_truncated:ident
369         );)*
370     ) => {
371         impl <T : EnumSetType> EnumSet<T> {$(
372             #[doc = "Returns a `"]
373             #[doc = $underlying_str]
374             #[doc = "` representing the elements of this set.\n\nIf the underlying bitset will \
375                      not fit in a `"]
376             #[doc = $underlying_str]
377             #[doc = "`, this method will panic."]
378             pub fn $to(&self) -> $underlying {
379                 self.$try_to().expect("Bitset will not fit into this type.")
380             }
381
382             #[doc = "Tries to return a `"]
383             #[doc = $underlying_str]
384             #[doc = "` representing the elements of this set.\n\nIf the underlying bitset will \
385                      not fit in a `"]
386             #[doc = $underlying_str]
387             #[doc = "`, this method will instead return `None`."]
388             pub fn $try_to(&self) -> Option<$underlying> {
389                 EnumSetTypeRepr::$to_fn_opt(&self.__priv_repr)
390             }
391
392             #[doc = "Returns a truncated `"]
393             #[doc = $underlying_str]
394             #[doc = "` representing the elements of this set.\n\nIf the underlying bitset will \
395                      not fit in a `"]
396             #[doc = $underlying_str]
397             #[doc = "`, this method will truncate any bits that don't fit."]
398             pub fn $to_truncated(&self) -> $underlying {
399                 EnumSetTypeRepr::$to_fn(&self.__priv_repr)
400             }
401
402             #[doc = "Constructs a bitset from a `"]
403             #[doc = $underlying_str]
404             #[doc = "`.\n\nIf a bit that doesn't correspond to an enum variant is set, this \
405                      method will panic."]
406             pub fn $from(bits: $underlying) -> Self {
407                 Self::$try_from(bits).expect("Bitset contains invalid variants.")
408             }
409
410             #[doc = "Attempts to constructs a bitset from a `"]
411             #[doc = $underlying_str]
412             #[doc = "`.\n\nIf a bit that doesn't correspond to an enum variant is set, this \
413                      method will return `None`."]
414             pub fn $try_from(bits: $underlying) -> Option<Self> {
415                 let bits = T::Repr::$from_fn_opt(bits);
416                 let mask = Self::all().__priv_repr;
417                 bits.and_then(|bits| if bits.and_not(mask).is_empty() {
418                     Some(EnumSet { __priv_repr: bits })
419                 } else {
420                     None
421                 })
422             }
423
424             #[doc = "Constructs a bitset from a `"]
425             #[doc = $underlying_str]
426             #[doc = "`, ignoring invalid variants."]
427             pub fn $from_truncated(bits: $underlying) -> Self {
428                 let mask = Self::all().$to_truncated();
429                 let bits = <T::Repr as EnumSetTypeRepr>::$from_fn(bits & mask);
430                 EnumSet { __priv_repr: bits }
431             }
432         )*}
433     }
434 }
435 conversion_impls! {
436     for_num!(u8, "u8", from_u8 to_u8 from_u8_opt to_u8_opt,
437              from_u8 try_from_u8 from_u8_truncated as_u8 try_as_u8 as_u8_truncated);
438     for_num!(u16, "u16", from_u16 to_u16 from_u16_opt to_u16_opt,
439              from_u16 try_from_u16 from_u16_truncated as_u16 try_as_u16 as_u16_truncated);
440     for_num!(u32, "u32", from_u32 to_u32 from_u32_opt to_u32_opt,
441              from_u32 try_from_u32 from_u32_truncated as_u32 try_as_u32 as_u32_truncated);
442     for_num!(u64, "u64", from_u64 to_u64 from_u64_opt to_u64_opt,
443              from_u64 try_from_u64 from_u64_truncated as_u64 try_as_u64 as_u64_truncated);
444     for_num!(u128, "u128", from_u128 to_u128 from_u128_opt to_u128_opt,
445              from_u128 try_from_u128 from_u128_truncated as_u128 try_as_u128 as_u128_truncated);
446     for_num!(usize, "usize", from_usize to_usize from_usize_opt to_usize_opt,
447              from_usize try_from_usize from_usize_truncated
448              as_usize try_as_usize as_usize_truncated);
449 }
450
451 impl <T: EnumSetType> Default for EnumSet<T> {
452     /// Returns an empty set.
453     fn default() -> Self {
454         Self::new()
455     }
456 }
457
458 impl <T: EnumSetType> IntoIterator for EnumSet<T> {
459     type Item = T;
460     type IntoIter = EnumSetIter<T>;
461
462     fn into_iter(self) -> Self::IntoIter {
463         self.iter()
464     }
465 }
466 impl <T: EnumSetType> Sum for EnumSet<T> {
467     fn sum<I: Iterator<Item=Self>>(iter: I) -> Self {
468         iter.fold(EnumSet::empty(), |a, v| a | v)
469     }
470 }
471 impl <'a, T: EnumSetType> Sum<&'a EnumSet<T>> for EnumSet<T> {
472     fn sum<I: Iterator<Item=&'a Self>>(iter: I) -> Self {
473         iter.fold(EnumSet::empty(), |a, v| a | *v)
474     }
475 }
476 impl <T: EnumSetType> Sum<T> for EnumSet<T> {
477     fn sum<I: Iterator<Item=T>>(iter: I) -> Self {
478         iter.fold(EnumSet::empty(), |a, v| a | v)
479     }
480 }
481 impl <'a, T: EnumSetType> Sum<&'a T> for EnumSet<T> {
482     fn sum<I: Iterator<Item=&'a T>>(iter: I) -> Self {
483         iter.fold(EnumSet::empty(), |a, v| a | *v)
484     }
485 }
486
487 impl <T: EnumSetType, O: Into<EnumSet<T>>> Sub<O> for EnumSet<T> {
488     type Output = Self;
489     fn sub(self, other: O) -> Self::Output {
490         self.difference(other.into())
491     }
492 }
493 impl <T: EnumSetType, O: Into<EnumSet<T>>> BitAnd<O> for EnumSet<T> {
494     type Output = Self;
495     fn bitand(self, other: O) -> Self::Output {
496         self.intersection(other.into())
497     }
498 }
499 impl <T: EnumSetType, O: Into<EnumSet<T>>> BitOr<O> for EnumSet<T> {
500     type Output = Self;
501     fn bitor(self, other: O) -> Self::Output {
502         self.union(other.into())
503     }
504 }
505 impl <T: EnumSetType, O: Into<EnumSet<T>>> BitXor<O> for EnumSet<T> {
506     type Output = Self;
507     fn bitxor(self, other: O) -> Self::Output {
508         self.symmetrical_difference(other.into())
509     }
510 }
511
512 impl <T: EnumSetType, O: Into<EnumSet<T>>> SubAssign<O> for EnumSet<T> {
513     fn sub_assign(&mut self, rhs: O) {
514         *self = *self - rhs;
515     }
516 }
517 impl <T: EnumSetType, O: Into<EnumSet<T>>> BitAndAssign<O> for EnumSet<T> {
518     fn bitand_assign(&mut self, rhs: O) {
519         *self = *self & rhs;
520     }
521 }
522 impl <T: EnumSetType, O: Into<EnumSet<T>>> BitOrAssign<O> for EnumSet<T> {
523     fn bitor_assign(&mut self, rhs: O) {
524         *self = *self | rhs;
525     }
526 }
527 impl <T: EnumSetType, O: Into<EnumSet<T>>> BitXorAssign<O> for EnumSet<T> {
528     fn bitxor_assign(&mut self, rhs: O) {
529         *self = *self ^ rhs;
530     }
531 }
532
533 impl <T: EnumSetType> Not for EnumSet<T> {
534     type Output = Self;
535     fn not(self) -> Self::Output {
536         self.complement()
537     }
538 }
539
540 impl <T: EnumSetType> From<T> for EnumSet<T> {
541     fn from(t: T) -> Self {
542         EnumSet::only(t)
543     }
544 }
545
546 impl <T: EnumSetType> PartialEq<T> for EnumSet<T> {
547     fn eq(&self, other: &T) -> bool {
548         self.__priv_repr == EnumSet::only(*other).__priv_repr
549     }
550 }
551 impl <T: EnumSetType + Debug> Debug for EnumSet<T> {
552     fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
553         let mut is_first = true;
554         f.write_str("EnumSet(")?;
555         for v in self.iter() {
556             if !is_first { f.write_str(" | ")?; }
557             is_first = false;
558             v.fmt(f)?;
559         }
560         f.write_str(")")?;
561         Ok(())
562     }
563 }
564
565 #[allow(clippy::derive_hash_xor_eq)] // This impl exists to change trait bounds only.
566 impl <T: EnumSetType> Hash for EnumSet<T> {
567     fn hash<H: Hasher>(&self, state: &mut H) {
568         self.__priv_repr.hash(state)
569     }
570 }
571 impl <T: EnumSetType> PartialOrd for EnumSet<T> {
572     fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
573         self.__priv_repr.partial_cmp(&other.__priv_repr)
574     }
575 }
576 impl <T: EnumSetType> Ord for EnumSet<T> {
577     fn cmp(&self, other: &Self) -> Ordering {
578         self.__priv_repr.cmp(&other.__priv_repr)
579     }
580 }
581
582 #[cfg(feature = "serde")]
583 impl <T: EnumSetType> Serialize for EnumSet<T> {
584     fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
585         T::serialize(*self, serializer)
586     }
587 }
588
589 #[cfg(feature = "serde")]
590 impl <'de, T: EnumSetType> Deserialize<'de> for EnumSet<T> {
591     fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
592         T::deserialize(deserializer)
593     }
594 }
595
596 /// The iterator used by [`EnumSet`]s.
597 #[derive(Clone, Debug)]
598 pub struct EnumSetIter<T: EnumSetType>(EnumSet<T>);
599 impl <T: EnumSetType> Iterator for EnumSetIter<T> {
600     type Item = T;
601
602     fn next(&mut self) -> Option<Self::Item> {
603         if self.0.is_empty() {
604             None
605         } else {
606             let bit = self.0.__priv_repr.trailing_zeros();
607             self.0.__priv_repr.remove_bit(bit);
608             unsafe { Some(T::enum_from_u32(bit)) }
609         }
610     }
611     fn size_hint(&self) -> (usize, Option<usize>) {
612         let left = self.0.len();
613         (left, Some(left))
614     }
615 }
616
617 impl<T: EnumSetType> ExactSizeIterator for EnumSetIter<T> {}
618
619 impl<T: EnumSetType> Extend<T> for EnumSet<T> {
620     fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I) {
621         iter.into_iter().for_each(|v| { self.insert(v); });
622     }
623 }
624
625 impl<T: EnumSetType> FromIterator<T> for EnumSet<T> {
626     fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self {
627         let mut set = EnumSet::default();
628         set.extend(iter);
629         set
630     }
631 }
632
633 impl<T: EnumSetType> Extend<EnumSet<T>> for EnumSet<T> {
634     fn extend<I: IntoIterator<Item = EnumSet<T>>>(&mut self, iter: I) {
635         iter.into_iter().for_each(|v| { self.insert_all(v); });
636     }
637 }
638
639 impl<T: EnumSetType> FromIterator<EnumSet<T>> for EnumSet<T> {
640     fn from_iter<I: IntoIterator<Item = EnumSet<T>>>(iter: I) -> Self {
641         let mut set = EnumSet::default();
642         set.extend(iter);
643         set
644     }
645 }
646
647 /// Creates a EnumSet literal, which can be used in const contexts.
648 ///
649 /// The syntax used is `enum_set!(Type::A | Type::B | Type::C)`. Each variant must be of the same
650 /// type, or a error will occur at compile-time.
651 ///
652 /// This macro accepts trailing `|`s to allow easier use in other macros.
653 ///
654 /// # Examples
655 ///
656 /// ```rust
657 /// # use enumset::*;
658 /// # #[derive(EnumSetType, Debug)] enum Enum { A, B, C }
659 /// const CONST_SET: EnumSet<Enum> = enum_set!(Enum::A | Enum::B);
660 /// assert_eq!(CONST_SET, Enum::A | Enum::B);
661 /// ```
662 ///
663 /// This macro is strongly typed. For example, the following will not compile:
664 ///
665 /// ```compile_fail
666 /// # use enumset::*;
667 /// # #[derive(EnumSetType, Debug)] enum Enum { A, B, C }
668 /// # #[derive(EnumSetType, Debug)] enum Enum2 { A, B, C }
669 /// let type_error = enum_set!(Enum::A | Enum2::B);
670 /// ```
671 #[macro_export]
672 macro_rules! enum_set {
673     ($(|)*) => {
674         $crate::EnumSet { __priv_repr: 0 }
675     };
676     ($value:path $(|)*) => {
677         {
678             #[allow(deprecated)] let value = $value.__impl_enumset_internal__const_only();
679             value
680         }
681     };
682     ($value:path | $($rest:path)|* $(|)*) => {
683         {
684             #[allow(deprecated)] let value = $value.__impl_enumset_internal__const_only();
685             $(#[allow(deprecated)] let value = $rest.__impl_enumset_internal__const_merge(value);)*
686             value
687         }
688     };
689 }