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