]> git.lizzy.rs Git - enumset.git/blob - enumset/src/lib.rs
b5656aa0791524370a2764dceedb44af7e1432ca
[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. These automatic
147 /// implementations can be disabled by adding an `#[enumset(no_super_impls)]` annotation to
148 /// the enum, but they must still be implemented. Disabling the automatic implementations can be
149 /// useful if, for example, you are using a code generator that already derives these traits. Note
150 /// that the `PartialEq` implementation, if not derived, **must** produce the same results as a
151 /// derived implementation would, or else `EnumSet` will not work correctly.
152 ///
153 /// In addition, if you have renamed the `enumset` crate in your crate, you can use the
154 /// `#[enumset(crate_name = "enumset2")]` attribute to tell the custom derive to use that name
155 /// instead.
156 ///
157 /// Attributes controlling the serialization of an `EnumSet` are documented in
158 /// [its documentation](./struct.EnumSet.html#serialization).
159 ///
160 /// # Examples
161 ///
162 /// Deriving a plain EnumSetType:
163 ///
164 /// ```rust
165 /// # use enumset::*;
166 /// #[derive(EnumSetType)]
167 /// pub enum Enum {
168 ///    A, B, C, D, E, F, G,
169 /// }
170 /// ```
171 ///
172 /// Deriving a sparse EnumSetType:
173 ///
174 /// ```rust
175 /// # use enumset::*;
176 /// #[derive(EnumSetType)]
177 /// pub enum SparseEnum {
178 ///    A = 10, B = 20, C = 30, D = 127,
179 /// }
180 /// ```
181 ///
182 /// Deriving an EnumSetType without adding ops:
183 ///
184 /// ```rust
185 /// # use enumset::*;
186 /// #[derive(EnumSetType)]
187 /// #[enumset(no_ops)]
188 /// pub enum NoOpsEnum {
189 ///    A, B, C, D, E, F, G,
190 /// }
191 /// ```
192 pub unsafe trait EnumSetType: Copy + Eq + EnumSetTypePrivate { }
193
194 /// An efficient set type for enums.
195 ///
196 /// It is implemented using a bitset stored using the smallest integer that can fit all bits
197 /// in the underlying enum. In general, an enum variant with a numeric value of `n` is stored in
198 /// the nth least significant bit (corresponding with a mask of, e.g. `1 << enum as u32`).
199 ///
200 /// # Serialization
201 ///
202 /// When the `serde` feature is enabled, `EnumSet`s can be serialized and deserialized using
203 /// the `serde` crate. The exact serialization format can be controlled with additional attributes
204 /// on the enum type. These attributes are valid regardless of whether the `serde` feature
205 /// is enabled.
206 ///
207 /// By default, `EnumSet`s serialize by directly writing out the underlying bitset as an integer
208 /// of the smallest type that can fit in the underlying enum. You can add a
209 /// `#[enumset(serialize_repr = "u8")]` attribute to your enum to control the integer type used
210 /// for serialization. This can be important for avoiding unintentional breaking changes when
211 /// `EnumSet`s are serialized with formats like `bincode`.
212 ///
213 /// By default, unknown bits are ignored and silently removed from the bitset. To override this
214 /// behavior, you can add a `#[enumset(serialize_deny_unknown)]` attribute. This will cause
215 /// deserialization to fail if an invalid bit is set.
216 ///
217 /// In addition, the `#[enumset(serialize_as_list)]` attribute causes the `EnumSet` to be
218 /// instead serialized as a list of enum variants. This requires your enum type implement
219 /// [`Serialize`] and [`Deserialize`]. Note that this is a breaking change
220 #[derive(Copy, Clone, PartialEq, Eq)]
221 #[repr(transparent)]
222 pub struct EnumSet<T: EnumSetType> {
223     #[doc(hidden)]
224     /// This is public due to the [`enum_set!`] macro.
225     /// This is **NOT** public API and may change at any time.
226     pub __priv_repr: T::Repr
227 }
228 impl <T: EnumSetType> EnumSet<T> {
229     // Returns all bits valid for the enum
230     #[inline(always)]
231     fn all_bits() -> T::Repr {
232         T::ALL_BITS
233     }
234
235     /// Creates an empty `EnumSet`.
236     #[inline(always)]
237     pub fn new() -> Self {
238         EnumSet { __priv_repr: T::Repr::empty() }
239     }
240
241     /// Returns an `EnumSet` containing a single element.
242     #[inline(always)]
243     pub fn only(t: T) -> Self {
244         let mut set = Self::new();
245         set.insert(t);
246         set
247     }
248
249     /// Creates an empty `EnumSet`.
250     ///
251     /// This is an alias for [`EnumSet::new`].
252     #[inline(always)]
253     pub fn empty() -> Self {
254         Self::new()
255     }
256
257     /// Returns an `EnumSet` containing all valid variants of the enum.
258     #[inline(always)]
259     pub fn all() -> Self {
260         EnumSet { __priv_repr: Self::all_bits() }
261     }
262
263     /// Total number of bits used by this type. Note that the actual amount of space used is
264     /// rounded up to the next highest integer type (`u8`, `u16`, `u32`, `u64`, or `u128`).
265     ///
266     /// This is the same as [`EnumSet::variant_count`] except in enums with "sparse" variants.
267     /// (e.g. `enum Foo { A = 10, B = 20 }`)
268     #[inline(always)]
269     pub fn bit_width() -> u32 {
270         T::Repr::WIDTH - T::ALL_BITS.leading_zeros()
271     }
272
273     /// The number of valid variants that this type can contain.
274     ///
275     /// This is the same as [`EnumSet::bit_width`] except in enums with "sparse" variants.
276     /// (e.g. `enum Foo { A = 10, B = 20 }`)
277     #[inline(always)]
278     pub fn variant_count() -> u32 {
279         T::ALL_BITS.count_ones()
280     }
281
282     /// Returns the number of elements in this set.
283     #[inline(always)]
284     pub fn len(&self) -> usize {
285         self.__priv_repr.count_ones() as usize
286     }
287     /// Returns `true` if the set contains no elements.
288     #[inline(always)]
289     pub fn is_empty(&self) -> bool {
290         self.__priv_repr.is_empty()
291     }
292     /// Removes all elements from the set.
293     #[inline(always)]
294     pub fn clear(&mut self) {
295         self.__priv_repr = T::Repr::empty()
296     }
297
298     /// Returns `true` if `self` has no elements in common with `other`. This is equivalent to
299     /// checking for an empty intersection.
300     #[inline(always)]
301     pub fn is_disjoint(&self, other: Self) -> bool {
302         (*self & other).is_empty()
303     }
304     /// Returns `true` if the set is a superset of another, i.e., `self` contains at least all the
305     /// values in `other`.
306     #[inline(always)]
307     pub fn is_superset(&self, other: Self) -> bool {
308         (*self & other).__priv_repr == other.__priv_repr
309     }
310     /// Returns `true` if the set is a subset of another, i.e., `other` contains at least all
311     /// the values in `self`.
312     #[inline(always)]
313     pub fn is_subset(&self, other: Self) -> bool {
314         other.is_superset(*self)
315     }
316
317     /// Returns a set containing any elements present in either set.
318     #[inline(always)]
319     pub fn union(&self, other: Self) -> Self {
320         EnumSet { __priv_repr: self.__priv_repr | other.__priv_repr }
321     }
322     /// Returns a set containing every element present in both sets.
323     #[inline(always)]
324     pub fn intersection(&self, other: Self) -> Self {
325         EnumSet { __priv_repr: self.__priv_repr & other.__priv_repr }
326     }
327     /// Returns a set containing element present in `self` but not in `other`.
328     #[inline(always)]
329     pub fn difference(&self, other: Self) -> Self {
330         EnumSet { __priv_repr: self.__priv_repr.and_not(other.__priv_repr) }
331     }
332     /// Returns a set containing every element present in either `self` or `other`, but is not
333     /// present in both.
334     #[inline(always)]
335     pub fn symmetrical_difference(&self, other: Self) -> Self {
336         EnumSet { __priv_repr: self.__priv_repr ^ other.__priv_repr }
337     }
338     /// Returns a set containing all enum variants not in this set.
339     #[inline(always)]
340     pub fn complement(&self) -> Self {
341         EnumSet { __priv_repr: !self.__priv_repr & Self::all_bits() }
342     }
343
344     /// Checks whether this set contains a value.
345     #[inline(always)]
346     pub fn contains(&self, value: T) -> bool {
347         self.__priv_repr.has_bit(value.enum_into_u32())
348     }
349
350     /// Adds a value to this set.
351     ///
352     /// If the set did not have this value present, `true` is returned.
353     ///
354     /// If the set did have this value present, `false` is returned.
355     #[inline(always)]
356     pub fn insert(&mut self, value: T) -> bool {
357         let contains = !self.contains(value);
358         self.__priv_repr.add_bit(value.enum_into_u32());
359         contains
360     }
361     /// Removes a value from this set. Returns whether the value was present in the set.
362     #[inline(always)]
363     pub fn remove(&mut self, value: T) -> bool {
364         let contains = self.contains(value);
365         self.__priv_repr.remove_bit(value.enum_into_u32());
366         contains
367     }
368
369     /// Adds all elements in another set to this one.
370     #[inline(always)]
371     pub fn insert_all(&mut self, other: Self) {
372         self.__priv_repr = self.__priv_repr | other.__priv_repr
373     }
374     /// Removes all values in another set from this one.
375     #[inline(always)]
376     pub fn remove_all(&mut self, other: Self) {
377         self.__priv_repr = self.__priv_repr.and_not(other.__priv_repr);
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::new(*self)
386     }
387 }
388
389 /// Helper macro for generating conversion functions.
390 macro_rules! conversion_impls {
391     (
392         $(for_num!(
393             $underlying:ty, $underlying_str:expr,
394             $from_fn:ident $to_fn:ident $from_fn_opt:ident $to_fn_opt:ident,
395             $from:ident $try_from:ident $from_truncated:ident
396             $to:ident $try_to:ident $to_truncated:ident
397         );)*
398     ) => {
399         impl <T : EnumSetType> EnumSet<T> {$(
400             #[doc = "Returns a `"]
401             #[doc = $underlying_str]
402             #[doc = "` representing the elements of this set.\n\nIf the underlying bitset will \
403                      not fit in a `"]
404             #[doc = $underlying_str]
405             #[doc = "`, this method will panic."]
406             #[inline(always)]
407             pub fn $to(&self) -> $underlying {
408                 self.$try_to().expect("Bitset will not fit into this type.")
409             }
410
411             #[doc = "Tries to return a `"]
412             #[doc = $underlying_str]
413             #[doc = "` representing the elements of this set.\n\nIf the underlying bitset will \
414                      not fit in a `"]
415             #[doc = $underlying_str]
416             #[doc = "`, this method will instead return `None`."]
417             #[inline(always)]
418             pub fn $try_to(&self) -> Option<$underlying> {
419                 EnumSetTypeRepr::$to_fn_opt(&self.__priv_repr)
420             }
421
422             #[doc = "Returns a truncated `"]
423             #[doc = $underlying_str]
424             #[doc = "` representing the elements of this set.\n\nIf the underlying bitset will \
425                      not fit in a `"]
426             #[doc = $underlying_str]
427             #[doc = "`, this method will truncate any bits that don't fit."]
428             #[inline(always)]
429             pub fn $to_truncated(&self) -> $underlying {
430                 EnumSetTypeRepr::$to_fn(&self.__priv_repr)
431             }
432
433             #[doc = "Constructs a bitset from a `"]
434             #[doc = $underlying_str]
435             #[doc = "`.\n\nIf a bit that doesn't correspond to an enum variant is set, this \
436                      method will panic."]
437             #[inline(always)]
438             pub fn $from(bits: $underlying) -> Self {
439                 Self::$try_from(bits).expect("Bitset contains invalid variants.")
440             }
441
442             #[doc = "Attempts to constructs a bitset from a `"]
443             #[doc = $underlying_str]
444             #[doc = "`.\n\nIf a bit that doesn't correspond to an enum variant is set, this \
445                      method will return `None`."]
446             #[inline(always)]
447             pub fn $try_from(bits: $underlying) -> Option<Self> {
448                 let bits = T::Repr::$from_fn_opt(bits);
449                 let mask = Self::all().__priv_repr;
450                 bits.and_then(|bits| if bits.and_not(mask).is_empty() {
451                     Some(EnumSet { __priv_repr: bits })
452                 } else {
453                     None
454                 })
455             }
456
457             #[doc = "Constructs a bitset from a `"]
458             #[doc = $underlying_str]
459             #[doc = "`, ignoring invalid variants."]
460             #[inline(always)]
461             pub fn $from_truncated(bits: $underlying) -> Self {
462                 let mask = Self::all().$to_truncated();
463                 let bits = <T::Repr as EnumSetTypeRepr>::$from_fn(bits & mask);
464                 EnumSet { __priv_repr: bits }
465             }
466         )*}
467     }
468 }
469 conversion_impls! {
470     for_num!(u8, "u8", from_u8 to_u8 from_u8_opt to_u8_opt,
471              from_u8 try_from_u8 from_u8_truncated as_u8 try_as_u8 as_u8_truncated);
472     for_num!(u16, "u16", from_u16 to_u16 from_u16_opt to_u16_opt,
473              from_u16 try_from_u16 from_u16_truncated as_u16 try_as_u16 as_u16_truncated);
474     for_num!(u32, "u32", from_u32 to_u32 from_u32_opt to_u32_opt,
475              from_u32 try_from_u32 from_u32_truncated as_u32 try_as_u32 as_u32_truncated);
476     for_num!(u64, "u64", from_u64 to_u64 from_u64_opt to_u64_opt,
477              from_u64 try_from_u64 from_u64_truncated as_u64 try_as_u64 as_u64_truncated);
478     for_num!(u128, "u128", from_u128 to_u128 from_u128_opt to_u128_opt,
479              from_u128 try_from_u128 from_u128_truncated as_u128 try_as_u128 as_u128_truncated);
480     for_num!(usize, "usize", from_usize to_usize from_usize_opt to_usize_opt,
481              from_usize try_from_usize from_usize_truncated
482              as_usize try_as_usize as_usize_truncated);
483 }
484
485 impl <T: EnumSetType> Default for EnumSet<T> {
486     /// Returns an empty set.
487     fn default() -> Self {
488         Self::new()
489     }
490 }
491
492 impl <T: EnumSetType> IntoIterator for EnumSet<T> {
493     type Item = T;
494     type IntoIter = EnumSetIter<T>;
495
496     fn into_iter(self) -> Self::IntoIter {
497         self.iter()
498     }
499 }
500 impl <T: EnumSetType> Sum for EnumSet<T> {
501     fn sum<I: Iterator<Item=Self>>(iter: I) -> Self {
502         iter.fold(EnumSet::empty(), |a, v| a | v)
503     }
504 }
505 impl <'a, T: EnumSetType> Sum<&'a EnumSet<T>> for EnumSet<T> {
506     fn sum<I: Iterator<Item=&'a Self>>(iter: I) -> Self {
507         iter.fold(EnumSet::empty(), |a, v| a | *v)
508     }
509 }
510 impl <T: EnumSetType> Sum<T> for EnumSet<T> {
511     fn sum<I: Iterator<Item=T>>(iter: I) -> Self {
512         iter.fold(EnumSet::empty(), |a, v| a | v)
513     }
514 }
515 impl <'a, T: EnumSetType> Sum<&'a T> for EnumSet<T> {
516     fn sum<I: Iterator<Item=&'a T>>(iter: I) -> Self {
517         iter.fold(EnumSet::empty(), |a, v| a | *v)
518     }
519 }
520
521 impl <T: EnumSetType, O: Into<EnumSet<T>>> Sub<O> for EnumSet<T> {
522     type Output = Self;
523     #[inline(always)]
524     fn sub(self, other: O) -> Self::Output {
525         self.difference(other.into())
526     }
527 }
528 impl <T: EnumSetType, O: Into<EnumSet<T>>> BitAnd<O> for EnumSet<T> {
529     type Output = Self;
530     #[inline(always)]
531     fn bitand(self, other: O) -> Self::Output {
532         self.intersection(other.into())
533     }
534 }
535 impl <T: EnumSetType, O: Into<EnumSet<T>>> BitOr<O> for EnumSet<T> {
536     type Output = Self;
537     #[inline(always)]
538     fn bitor(self, other: O) -> Self::Output {
539         self.union(other.into())
540     }
541 }
542 impl <T: EnumSetType, O: Into<EnumSet<T>>> BitXor<O> for EnumSet<T> {
543     type Output = Self;
544     #[inline(always)]
545     fn bitxor(self, other: O) -> Self::Output {
546         self.symmetrical_difference(other.into())
547     }
548 }
549
550 impl <T: EnumSetType, O: Into<EnumSet<T>>> SubAssign<O> for EnumSet<T> {
551     #[inline(always)]
552     fn sub_assign(&mut self, rhs: O) {
553         *self = *self - rhs;
554     }
555 }
556 impl <T: EnumSetType, O: Into<EnumSet<T>>> BitAndAssign<O> for EnumSet<T> {
557     #[inline(always)]
558     fn bitand_assign(&mut self, rhs: O) {
559         *self = *self & rhs;
560     }
561 }
562 impl <T: EnumSetType, O: Into<EnumSet<T>>> BitOrAssign<O> for EnumSet<T> {
563     #[inline(always)]
564     fn bitor_assign(&mut self, rhs: O) {
565         *self = *self | rhs;
566     }
567 }
568 impl <T: EnumSetType, O: Into<EnumSet<T>>> BitXorAssign<O> for EnumSet<T> {
569     #[inline(always)]
570     fn bitxor_assign(&mut self, rhs: O) {
571         *self = *self ^ rhs;
572     }
573 }
574
575 impl <T: EnumSetType> Not for EnumSet<T> {
576     type Output = Self;
577     #[inline(always)]
578     fn not(self) -> Self::Output {
579         self.complement()
580     }
581 }
582
583 impl <T: EnumSetType> From<T> for EnumSet<T> {
584     fn from(t: T) -> Self {
585         EnumSet::only(t)
586     }
587 }
588
589 impl <T: EnumSetType> PartialEq<T> for EnumSet<T> {
590     fn eq(&self, other: &T) -> bool {
591         self.__priv_repr == EnumSet::only(*other).__priv_repr
592     }
593 }
594 impl <T: EnumSetType + Debug> Debug for EnumSet<T> {
595     fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
596         let mut is_first = true;
597         f.write_str("EnumSet(")?;
598         for v in self.iter() {
599             if !is_first { f.write_str(" | ")?; }
600             is_first = false;
601             v.fmt(f)?;
602         }
603         f.write_str(")")?;
604         Ok(())
605     }
606 }
607
608 #[allow(clippy::derive_hash_xor_eq)] // This impl exists to change trait bounds only.
609 impl <T: EnumSetType> Hash for EnumSet<T> {
610     fn hash<H: Hasher>(&self, state: &mut H) {
611         self.__priv_repr.hash(state)
612     }
613 }
614 impl <T: EnumSetType> PartialOrd for EnumSet<T> {
615     fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
616         self.__priv_repr.partial_cmp(&other.__priv_repr)
617     }
618 }
619 impl <T: EnumSetType> Ord for EnumSet<T> {
620     fn cmp(&self, other: &Self) -> Ordering {
621         self.__priv_repr.cmp(&other.__priv_repr)
622     }
623 }
624
625 #[cfg(feature = "serde")]
626 impl <T: EnumSetType> Serialize for EnumSet<T> {
627     fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
628         T::serialize(*self, serializer)
629     }
630 }
631
632 #[cfg(feature = "serde")]
633 impl <'de, T: EnumSetType> Deserialize<'de> for EnumSet<T> {
634     fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
635         T::deserialize(deserializer)
636     }
637 }
638
639 /// The iterator used by [`EnumSet`]s.
640 #[derive(Clone, Debug)]
641 pub struct EnumSetIter<T: EnumSetType> {
642     set: EnumSet<T>,
643 }
644 impl <T: EnumSetType> EnumSetIter<T> {
645     fn new(set: EnumSet<T>) -> EnumSetIter<T> {
646         EnumSetIter { set }
647     }
648 }
649 impl <T: EnumSetType> Iterator for EnumSetIter<T> {
650     type Item = T;
651
652     fn next(&mut self) -> Option<Self::Item> {
653         if self.set.is_empty() {
654             None
655         } else {
656             let bit = self.set.__priv_repr.trailing_zeros();
657             self.set.__priv_repr.remove_bit(bit);
658             unsafe { Some(T::enum_from_u32(bit)) }
659         }
660     }
661     fn size_hint(&self) -> (usize, Option<usize>) {
662         let left = self.set.len();
663         (left, Some(left))
664     }
665 }
666
667 impl<T: EnumSetType> ExactSizeIterator for EnumSetIter<T> {}
668
669 impl<T: EnumSetType> Extend<T> for EnumSet<T> {
670     fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I) {
671         iter.into_iter().for_each(|v| { self.insert(v); });
672     }
673 }
674
675 impl<T: EnumSetType> FromIterator<T> for EnumSet<T> {
676     fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self {
677         let mut set = EnumSet::default();
678         set.extend(iter);
679         set
680     }
681 }
682
683 impl<T: EnumSetType> Extend<EnumSet<T>> for EnumSet<T> {
684     fn extend<I: IntoIterator<Item = EnumSet<T>>>(&mut self, iter: I) {
685         iter.into_iter().for_each(|v| { self.insert_all(v); });
686     }
687 }
688
689 impl<T: EnumSetType> FromIterator<EnumSet<T>> for EnumSet<T> {
690     fn from_iter<I: IntoIterator<Item = EnumSet<T>>>(iter: I) -> Self {
691         let mut set = EnumSet::default();
692         set.extend(iter);
693         set
694     }
695 }
696
697 /// Creates a EnumSet literal, which can be used in const contexts.
698 ///
699 /// The syntax used is `enum_set!(Type::A | Type::B | Type::C)`. Each variant must be of the same
700 /// type, or a error will occur at compile-time.
701 ///
702 /// This macro accepts trailing `|`s to allow easier use in other macros.
703 ///
704 /// # Examples
705 ///
706 /// ```rust
707 /// # use enumset::*;
708 /// # #[derive(EnumSetType, Debug)] enum Enum { A, B, C }
709 /// const CONST_SET: EnumSet<Enum> = enum_set!(Enum::A | Enum::B);
710 /// assert_eq!(CONST_SET, Enum::A | Enum::B);
711 /// ```
712 ///
713 /// This macro is strongly typed. For example, the following will not compile:
714 ///
715 /// ```compile_fail
716 /// # use enumset::*;
717 /// # #[derive(EnumSetType, Debug)] enum Enum { A, B, C }
718 /// # #[derive(EnumSetType, Debug)] enum Enum2 { A, B, C }
719 /// let type_error = enum_set!(Enum::A | Enum2::B);
720 /// ```
721 #[macro_export]
722 macro_rules! enum_set {
723     ($(|)*) => {
724         $crate::EnumSet { __priv_repr: 0 }
725     };
726     ($value:path $(|)*) => {
727         {
728             #[allow(deprecated)] let value = $value.__impl_enumset_internal__const_only();
729             value
730         }
731     };
732     ($value:path | $($rest:path)|* $(|)*) => {
733         {
734             #[allow(deprecated)] let value = $value.__impl_enumset_internal__const_only();
735             $(#[allow(deprecated)] let value = $rest.__impl_enumset_internal__const_merge(value);)*
736             value
737         }
738     };
739 }