]> git.lizzy.rs Git - enumset.git/blob - enumset/src/lib.rs
Documentation improvements.
[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::*;
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;
85 use core::ops::*;
86
87 use num_traits::*;
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 struct used to type check [`enum_set!`].
95     pub struct EnumSetSameTypeHack<'a, T: EnumSetType + 'static> {
96         pub unified: &'a [T],
97         pub enum_set: EnumSet<T>,
98     }
99
100     /// A reexport of core to allow our macros to be generic to std vs core.
101     pub use ::core as core_export;
102
103     /// A reexport of serde so there is no requirement to depend on serde.
104     #[cfg(feature = "serde")] pub use serde2 as serde;
105
106     /// The actual members of EnumSetType. Put here to avoid polluting global namespaces.
107     pub unsafe trait EnumSetTypePrivate {
108         /// The underlying type used to store the bitset.
109         type Repr: EnumSetTypeRepr;
110         /// A mask of bits that are valid in the bitset.
111         const ALL_BITS: Self::Repr;
112
113         /// Converts an enum of this type into its bit position.
114         fn enum_into_u32(self) -> u32;
115         /// Converts a bit position into an enum value.
116         unsafe fn enum_from_u32(val: u32) -> Self;
117
118         /// Serializes the `EnumSet`.
119         ///
120         /// This and `deserialize` are part of the `EnumSetType` trait so the procedural derive
121         /// can control how `EnumSet` is serialized.
122         #[cfg(feature = "serde")]
123         fn serialize<S: serde::Serializer>(set: EnumSet<Self>, ser: S) -> Result<S::Ok, S::Error>
124             where Self: EnumSetType;
125         /// Deserializes the `EnumSet`.
126         #[cfg(feature = "serde")]
127         fn deserialize<'de, D: serde::Deserializer<'de>>(de: D) -> Result<EnumSet<Self>, D::Error>
128             where Self: EnumSetType;
129     }
130 }
131 use crate::__internal::EnumSetTypePrivate;
132 #[cfg(feature = "serde")] use crate::__internal::serde;
133 #[cfg(feature = "serde")] use crate::serde::{Serialize, Deserialize};
134
135 mod private {
136     use super::*;
137
138     /// A trait marking valid underlying bitset storage types and providing the
139     /// operations `EnumSet` and related types use.
140     pub trait EnumSetTypeRepr :
141         PrimInt + WrappingSub + CheckedShl + Debug + Hash + FromPrimitive + ToPrimitive +
142         AsPrimitive<u8> + AsPrimitive<u16> + AsPrimitive<u32> + AsPrimitive<u64> +
143         AsPrimitive<u128> + AsPrimitive<usize>
144     {
145         const WIDTH: u32;
146
147         fn from_u8(v: u8) -> Self;
148         fn from_u16(v: u16) -> Self;
149         fn from_u32(v: u32) -> Self;
150         fn from_u64(v: u64) -> Self;
151         fn from_u128(v: u128) -> Self;
152         fn from_usize(v: usize) -> Self;
153     }
154     macro_rules! prim {
155         ($name:ty, $width:expr) => {
156             impl EnumSetTypeRepr for $name {
157                 const WIDTH: u32 = $width;
158                 fn from_u8(v: u8) -> Self { v.as_() }
159                 fn from_u16(v: u16) -> Self { v.as_() }
160                 fn from_u32(v: u32) -> Self { v.as_() }
161                 fn from_u64(v: u64) -> Self { v.as_() }
162                 fn from_u128(v: u128) -> Self { v.as_() }
163                 fn from_usize(v: usize) -> Self { v.as_() }
164             }
165         }
166     }
167     prim!(u8  , 8  );
168     prim!(u16 , 16 );
169     prim!(u32 , 32 );
170     prim!(u64 , 64 );
171     prim!(u128, 128);
172 }
173 use crate::private::EnumSetTypeRepr;
174
175 /// The trait used to define enum types that may be used with [`EnumSet`].
176 ///
177 /// This trait should be implemented using `#[derive(EnumSetType)]`. Its internal structure is
178 /// not stable, and may change at any time.
179 ///
180 /// # Custom Derive
181 ///
182 /// Any C-like enum is supported, as long as there are no more than 128 variants in the enum,
183 /// and no variant discriminator is larger than 127.
184 ///
185 /// The custom derive for [`EnumSetType`] automatically creates implementations of [`PartialEq`],
186 /// [`Sub`], [`BitAnd`], [`BitOr`], [`BitXor`], and [`Not`] allowing the enum to be used as
187 /// if it were an [`EnumSet`] in expressions. This can be disabled by adding an `#[enumset(no_ops)]`
188 /// annotation to the enum.
189 ///
190 /// The custom derive for `EnumSetType` automatically implements [`Copy`], [`Clone`], [`Eq`], and
191 /// [`PartialEq`] on the enum. These are required for the [`EnumSet`] to function.
192 ///
193 /// In addition, if you have renamed the `enumset` crate in your crate, you can use the
194 /// `#[enumset(crate_name = "enumset2")]` attribute to tell the custom derive to use that name
195 /// instead.
196 ///
197 /// Attributes controlling the serialization of an `EnumSet` are documented in
198 /// [its documentation](./struct.EnumSet.html#serialization).
199 ///
200 /// # Examples
201 ///
202 /// Deriving a plain EnumSetType:
203 ///
204 /// ```rust
205 /// # use enumset::*;
206 /// #[derive(EnumSetType)]
207 /// pub enum Enum {
208 ///    A, B, C, D, E, F, G,
209 /// }
210 /// ```
211 ///
212 /// Deriving a sparse EnumSetType:
213 ///
214 /// ```rust
215 /// # use enumset::*;
216 /// #[derive(EnumSetType)]
217 /// pub enum SparseEnum {
218 ///    A = 10, B = 20, C = 30, D = 127,
219 /// }
220 /// ```
221 ///
222 /// Deriving an EnumSetType without adding ops:
223 ///
224 /// ```rust
225 /// # use enumset::*;
226 /// #[derive(EnumSetType)]
227 /// #[enumset(no_ops)]
228 /// pub enum NoOpsEnum {
229 ///    A, B, C, D, E, F, G,
230 /// }
231 /// ```
232 pub unsafe trait EnumSetType: Copy + Eq + EnumSetTypePrivate { }
233
234 /// An efficient set type for enums.
235 ///
236 /// It is implemented using a bitset stored using the smallest integer that can fit all bits
237 /// in the underlying enum. In general, an enum variant with a numeric value of `n` is stored in
238 /// the nth least significant bit (corresponding with a mask of, e.g. `1 << enum as u32`).
239 ///
240 /// # Serialization
241 ///
242 /// When the `serde` feature is enabled, `EnumSet`s can be serialized and deserialized using
243 /// the `serde` crate. The exact serialization format can be controlled with additional attributes
244 /// on the enum type. These attributes are valid regardless of whether the `serde` feature
245 /// is enabled.
246 ///
247 /// By default, `EnumSet`s serialize by directly writing out the underlying bitset as an integer
248 /// of the smallest type that can fit in the underlying enum. You can add a
249 /// `#[enumset(serialize_repr = "u8")]` attribute to your enum to control the integer type used
250 /// for serialization. This can be important for avoiding unintentional breaking changes when
251 /// `EnumSet`s are serialized with formats like `bincode`.
252 ///
253 /// By default, unknown bits are ignored and silently removed from the bitset. To override this
254 /// behavior, you can add a `#[enumset(serialize_deny_unknown)]` attribute. This will cause
255 /// deserialization to fail if an invalid bit is set.
256 ///
257 /// In addition, the `#[enumset(serialize_as_list)]` attribute causes the `EnumSet` to be
258 /// instead serialized as a list of enum variants. This requires your enum type implement
259 /// [`Serialize`] and [`Deserialize`]. Note that this is a breaking change
260 #[derive(Copy, Clone, PartialEq, Eq)]
261 pub struct EnumSet<T: EnumSetType> {
262     #[doc(hidden)]
263     /// This is public due to the [`enum_set!`] macro.
264     /// This is **NOT** public API and may change at any time.
265     pub __enumset_underlying: T::Repr
266 }
267 impl <T: EnumSetType> EnumSet<T> {
268     fn mask(bit: u32) -> T::Repr {
269         Shl::<usize>::shl(T::Repr::one(), bit as usize)
270     }
271     fn has_bit(&self, bit: u32) -> bool {
272         let mask = Self::mask(bit);
273         self.__enumset_underlying & mask == mask
274     }
275     fn partial_bits(bits: u32) -> T::Repr {
276         T::Repr::one().checked_shl(bits as u32)
277             .unwrap_or(T::Repr::zero())
278             .wrapping_sub(&T::Repr::one())
279     }
280
281     // Returns all bits valid for the enum
282     fn all_bits() -> T::Repr {
283         T::ALL_BITS
284     }
285
286     /// Creates an empty `EnumSet`.
287     pub fn new() -> Self {
288         EnumSet { __enumset_underlying: T::Repr::zero() }
289     }
290
291     /// Returns an `EnumSet` containing a single element.
292     pub fn only(t: T) -> Self {
293         EnumSet { __enumset_underlying: Self::mask(t.enum_into_u32()) }
294     }
295
296     /// Creates an empty `EnumSet`.
297     ///
298     /// This is an alias for [`EnumSet::new`].
299     pub fn empty() -> Self {
300         Self::new()
301     }
302
303     /// Returns an `EnumSet` containing all valid variants of the enum.
304     pub fn all() -> Self {
305         EnumSet { __enumset_underlying: Self::all_bits() }
306     }
307
308     /// Total number of bits used by this type. Note that the actual amount of space used is
309     /// rounded up to the next highest integer type (`u8`, `u16`, `u32`, `u64`, or `u128`).
310     ///
311     /// This is the same as [`EnumSet::variant_count`] except in enums with "sparse" variants.
312     /// (e.g. `enum Foo { A = 10, B = 20 }`)
313     pub fn bit_width() -> u32 {
314         T::Repr::WIDTH - T::ALL_BITS.leading_zeros()
315     }
316
317     /// The number of valid variants that this type can contain.
318     ///
319     /// This is the same as [`EnumSet::bit_width`] except in enums with "sparse" variants.
320     /// (e.g. `enum Foo { A = 10, B = 20 }`)
321     pub fn variant_count() -> u32 {
322         T::ALL_BITS.count_ones()
323     }
324
325     /// Returns the number of elements in this set.
326     pub fn len(&self) -> usize {
327         self.__enumset_underlying.count_ones() as usize
328     }
329     /// Returns `true` if the set contains no elements.
330     pub fn is_empty(&self) -> bool {
331         self.__enumset_underlying.is_zero()
332     }
333     /// Removes all elements from the set.
334     pub fn clear(&mut self) {
335         self.__enumset_underlying = T::Repr::zero()
336     }
337
338     /// Returns `true` if `self` has no elements in common with `other`. This is equivalent to
339     /// checking for an empty intersection.
340     pub fn is_disjoint(&self, other: Self) -> bool {
341         (*self & other).is_empty()
342     }
343     /// Returns `true` if the set is a superset of another, i.e., `self` contains at least all the
344     /// values in `other`.
345     pub fn is_superset(&self, other: Self) -> bool {
346         (*self & other).__enumset_underlying == other.__enumset_underlying
347     }
348     /// Returns `true` if the set is a subset of another, i.e., `other` contains at least all
349     /// the values in `self`.
350     pub fn is_subset(&self, other: Self) -> bool {
351         other.is_superset(*self)
352     }
353
354     /// Returns a set containing any elements present in either set.
355     pub fn union(&self, other: Self) -> Self {
356         EnumSet { __enumset_underlying: self.__enumset_underlying | other.__enumset_underlying }
357     }
358     /// Returns a set containing every element present in both sets.
359     pub fn intersection(&self, other: Self) -> Self {
360         EnumSet { __enumset_underlying: self.__enumset_underlying & other.__enumset_underlying }
361     }
362     /// Returns a set containing element present in `self` but not in `other`.
363     pub fn difference(&self, other: Self) -> Self {
364         EnumSet { __enumset_underlying: self.__enumset_underlying & !other.__enumset_underlying }
365     }
366     /// Returns a set containing every element present in either `self` or `other`, but is not
367     /// present in both.
368     pub fn symmetrical_difference(&self, other: Self) -> Self {
369         EnumSet { __enumset_underlying: self.__enumset_underlying ^ other.__enumset_underlying }
370     }
371     /// Returns a set containing all enum variants not in this set.
372     pub fn complement(&self) -> Self {
373         EnumSet { __enumset_underlying: !self.__enumset_underlying & Self::all_bits() }
374     }
375
376     /// Checks whether this set contains a value.
377     pub fn contains(&self, value: T) -> bool {
378         self.has_bit(value.enum_into_u32())
379     }
380
381     /// Adds a value to this set.
382     ///
383     /// If the set did not have this value present, `true` is returned.
384     ///
385     /// If the set did have this value present, `false` is returned.
386     pub fn insert(&mut self, value: T) -> bool {
387         let contains = !self.contains(value);
388         self.__enumset_underlying = self.__enumset_underlying | Self::mask(value.enum_into_u32());
389         contains
390     }
391     /// Removes a value from this set. Returns whether the value was present in the set.
392     pub fn remove(&mut self, value: T) -> bool {
393         let contains = self.contains(value);
394         self.__enumset_underlying = self.__enumset_underlying & !Self::mask(value.enum_into_u32());
395         contains
396     }
397
398     /// Adds all elements in another set to this one.
399     pub fn insert_all(&mut self, other: Self) {
400         self.__enumset_underlying = self.__enumset_underlying | other.__enumset_underlying
401     }
402     /// Removes all values in another set from this one.
403     pub fn remove_all(&mut self, other: Self) {
404         self.__enumset_underlying = self.__enumset_underlying & !other.__enumset_underlying
405     }
406
407     /// Creates an iterator over the values in this set.
408     ///
409     /// Note that iterator invalidation is impossible as the iterator contains a copy of this type,
410     /// rather than holding a reference to it.
411     pub fn iter(&self) -> EnumSetIter<T> {
412         EnumSetIter(*self, 0)
413     }
414 }
415
416 /// Helper macro for generating conversion functions.
417 macro_rules! conversion_impls {
418     (
419         $(for_num!(
420             $underlying:ty, $underlying_str:expr, $from_fn:ident, $to_fn: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             pub fn $to(&self) -> $underlying {
433                 self.$try_to().expect("Bitset will not fit into this type.")
434             }
435
436             #[doc = "Tries to return a `"]
437             #[doc = $underlying_str]
438             #[doc = "` representing the elements of this set.\n\nIf the underlying bitset will \
439                      not fit in a `"]
440             #[doc = $underlying_str]
441             #[doc = "`, this method will instead return `None`."]
442             pub fn $try_to(&self) -> Option<$underlying> {
443                 self.__enumset_underlying.$to_fn()
444             }
445
446             #[doc = "Returns a truncated `"]
447             #[doc = $underlying_str]
448             #[doc = "` representing the elements of this set.\n\nIf the underlying bitset will \
449                      not fit in a `"]
450             #[doc = $underlying_str]
451             #[doc = "`, this method will truncate any bits that don't fit."]
452             pub fn $to_truncated(&self) -> $underlying {
453                 AsPrimitive::<$underlying>::as_(self.__enumset_underlying)
454             }
455
456             #[doc = "Constructs a bitset from a `"]
457             #[doc = $underlying_str]
458             #[doc = "`.\n\nIf a bit that doesn't correspond to an enum variant is set, this \
459                      method will panic."]
460             pub fn $from(bits: $underlying) -> Self {
461                 Self::$try_from(bits).expect("Bitset contains invalid variants.")
462             }
463
464             #[doc = "Attempts to constructs a bitset from a `"]
465             #[doc = $underlying_str]
466             #[doc = "`.\n\nIf a bit that doesn't correspond to an enum variant is set, this \
467                      method will return `None`."]
468             pub fn $try_from(bits: $underlying) -> Option<Self> {
469                 let bits = <T::Repr as FromPrimitive>::$from_fn(bits);
470                 let mask = Self::all().__enumset_underlying;
471                 bits.and_then(|bits| if (bits & !mask) == T::Repr::zero() {
472                     Some(EnumSet { __enumset_underlying: bits })
473                 } else {
474                     None
475                 })
476             }
477
478             #[doc = "Constructs a bitset from a `"]
479             #[doc = $underlying_str]
480             #[doc = "`, ignoring invalid variants."]
481             pub fn $from_truncated(bits: $underlying) -> Self {
482                 let mask = Self::all().$to_truncated();
483                 let bits = <T::Repr as EnumSetTypeRepr>::$from_fn(bits & mask);
484                 EnumSet { __enumset_underlying: bits }
485             }
486         )*}
487     }
488 }
489 conversion_impls! {
490     for_num!(u8, "u8", from_u8, to_u8,
491              from_u8 try_from_u8 from_u8_truncated as_u8 try_as_u8 as_u8_truncated);
492     for_num!(u16, "u16", from_u16, to_u16,
493              from_u16 try_from_u16 from_u16_truncated as_u16 try_as_u16 as_u16_truncated);
494     for_num!(u32, "u32", from_u32, to_u32,
495              from_u32 try_from_u32 from_u32_truncated as_u32 try_as_u32 as_u32_truncated);
496     for_num!(u64, "u64", from_u64, to_u64,
497              from_u64 try_from_u64 from_u64_truncated as_u64 try_as_u64 as_u64_truncated);
498     for_num!(u128, "u128", from_u128, to_u128,
499              from_u128 try_from_u128 from_u128_truncated as_u128 try_as_u128 as_u128_truncated);
500     for_num!(usize, "usize", from_usize, to_usize,
501              from_usize try_from_usize from_usize_truncated
502              as_usize try_as_usize as_usize_truncated);
503 }
504
505 impl <T: EnumSetType> Default for EnumSet<T> {
506     /// Returns an empty set.
507     fn default() -> Self {
508         Self::new()
509     }
510 }
511
512 impl <T: EnumSetType> IntoIterator for EnumSet<T> {
513     type Item = T;
514     type IntoIter = EnumSetIter<T>;
515
516     fn into_iter(self) -> Self::IntoIter {
517         self.iter()
518     }
519 }
520
521 impl <T: EnumSetType, O: Into<EnumSet<T>>> Sub<O> for EnumSet<T> {
522     type Output = Self;
523     fn sub(self, other: O) -> Self::Output {
524         self.difference(other.into())
525     }
526 }
527 impl <T: EnumSetType, O: Into<EnumSet<T>>> BitAnd<O> for EnumSet<T> {
528     type Output = Self;
529     fn bitand(self, other: O) -> Self::Output {
530         self.intersection(other.into())
531     }
532 }
533 impl <T: EnumSetType, O: Into<EnumSet<T>>> BitOr<O> for EnumSet<T> {
534     type Output = Self;
535     fn bitor(self, other: O) -> Self::Output {
536         self.union(other.into())
537     }
538 }
539 impl <T: EnumSetType, O: Into<EnumSet<T>>> BitXor<O> for EnumSet<T> {
540     type Output = Self;
541     fn bitxor(self, other: O) -> Self::Output {
542         self.symmetrical_difference(other.into())
543     }
544 }
545
546 impl <T: EnumSetType, O: Into<EnumSet<T>>> SubAssign<O> for EnumSet<T> {
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     fn bitand_assign(&mut self, rhs: O) {
553         *self = *self & rhs;
554     }
555 }
556 impl <T: EnumSetType, O: Into<EnumSet<T>>> BitOrAssign<O> for EnumSet<T> {
557     fn bitor_assign(&mut self, rhs: O) {
558         *self = *self | rhs;
559     }
560 }
561 impl <T: EnumSetType, O: Into<EnumSet<T>>> BitXorAssign<O> for EnumSet<T> {
562     fn bitxor_assign(&mut self, rhs: O) {
563         *self = *self ^ rhs;
564     }
565 }
566
567 impl <T: EnumSetType> Not for EnumSet<T> {
568     type Output = Self;
569     fn not(self) -> Self::Output {
570         self.complement()
571     }
572 }
573
574 impl <T: EnumSetType> From<T> for EnumSet<T> {
575     fn from(t: T) -> Self {
576         EnumSet::only(t)
577     }
578 }
579
580 impl <T: EnumSetType> PartialEq<T> for EnumSet<T> {
581     fn eq(&self, other: &T) -> bool {
582         self.__enumset_underlying == EnumSet::<T>::mask(other.enum_into_u32())
583     }
584 }
585 impl <T: EnumSetType + Debug> Debug for EnumSet<T> {
586     fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
587         let mut is_first = true;
588         f.write_str("EnumSet(")?;
589         for v in self.iter() {
590             if !is_first { f.write_str(" | ")?; }
591             is_first = false;
592             v.fmt(f)?;
593         }
594         f.write_str(")")?;
595         Ok(())
596     }
597 }
598
599 impl <T: EnumSetType> Hash for EnumSet<T> {
600     fn hash<H: Hasher>(&self, state: &mut H) {
601         self.__enumset_underlying.hash(state)
602     }
603 }
604 impl <T: EnumSetType> PartialOrd for EnumSet<T> {
605     fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
606         self.__enumset_underlying.partial_cmp(&other.__enumset_underlying)
607     }
608 }
609 impl <T: EnumSetType> Ord for EnumSet<T> {
610     fn cmp(&self, other: &Self) -> Ordering {
611         self.__enumset_underlying.cmp(&other.__enumset_underlying)
612     }
613 }
614
615 #[cfg(feature = "serde")]
616 impl <T: EnumSetType> Serialize for EnumSet<T> {
617     fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
618         T::serialize(*self, serializer)
619     }
620 }
621
622 #[cfg(feature = "serde")]
623 impl <'de, T: EnumSetType> Deserialize<'de> for EnumSet<T> {
624     fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
625         T::deserialize(deserializer)
626     }
627 }
628
629 /// The iterator used by [`EnumSet`]s.
630 #[derive(Clone, Debug)]
631 pub struct EnumSetIter<T: EnumSetType>(EnumSet<T>, u32);
632 impl <T: EnumSetType> Iterator for EnumSetIter<T> {
633     type Item = T;
634
635     fn next(&mut self) -> Option<Self::Item> {
636         while self.1 < EnumSet::<T>::bit_width() {
637             let bit = self.1;
638             self.1 += 1;
639             if self.0.has_bit(bit) {
640                 return unsafe { Some(T::enum_from_u32(bit)) }
641             }
642         }
643         None
644     }
645     fn size_hint(&self) -> (usize, Option<usize>) {
646         let left_mask = !EnumSet::<T>::partial_bits(self.1);
647         let left = (self.0.__enumset_underlying & left_mask).count_ones() as usize;
648         (left, Some(left))
649     }
650 }
651
652 impl<T: EnumSetType> Extend<T> for EnumSet<T> {
653     fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I) {
654         iter.into_iter().for_each(|v| { self.insert(v); });
655     }
656 }
657
658 impl<T: EnumSetType> FromIterator<T> for EnumSet<T> {
659     fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self {
660         let mut set = EnumSet::default();
661         set.extend(iter);
662         set
663     }
664 }
665
666 impl<T: EnumSetType> Extend<EnumSet<T>> for EnumSet<T> {
667     fn extend<I: IntoIterator<Item = EnumSet<T>>>(&mut self, iter: I) {
668         iter.into_iter().for_each(|v| { self.insert_all(v); });
669     }
670 }
671
672 impl<T: EnumSetType> FromIterator<EnumSet<T>> for EnumSet<T> {
673     fn from_iter<I: IntoIterator<Item = EnumSet<T>>>(iter: I) -> Self {
674         let mut set = EnumSet::default();
675         set.extend(iter);
676         set
677     }
678 }
679
680 /// Creates a EnumSet literal, which can be used in const contexts.
681 ///
682 /// The syntax used is `enum_set!(Type::A | Type::B | Type::C)`. Each variant must be of the same
683 /// type, or a error will occur at compile-time.
684 ///
685 /// # Examples
686 ///
687 /// ```rust
688 /// # use enumset::*;
689 /// # #[derive(EnumSetType, Debug)] enum Enum { A, B, C }
690 /// const CONST_SET: EnumSet<Enum> = enum_set!(Enum::A | Enum::B);
691 /// assert_eq!(CONST_SET, Enum::A | Enum::B);
692 /// ```
693 ///
694 /// This macro is strongly typed. For example, the following will not compile:
695 ///
696 /// ```compile_fail
697 /// # use enumset::*;
698 /// # #[derive(EnumSetType, Debug)] enum Enum { A, B, C }
699 /// # #[derive(EnumSetType, Debug)] enum Enum2 { A, B, C }
700 /// let type_error = enum_set!(Enum::A | Enum2::B);
701 /// ```
702 #[macro_export]
703 macro_rules! enum_set {
704     () => {
705         $crate::EnumSet { __enumset_underlying: 0 }
706     };
707     ($($value:path)|* $(|)*) => {
708         $crate::__internal::EnumSetSameTypeHack {
709             unified: &[$($value,)*],
710             enum_set: $crate::EnumSet {
711                 __enumset_underlying: 0 $(| (1 << ($value as u32)))*
712             },
713         }.enum_set
714     };
715 }