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