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