]> git.lizzy.rs Git - enumset.git/blob - enumset/src/lib.rs
Implement option to serialize enumsets as lists.
[enumset.git] / enumset / src / lib.rs
1 #![cfg_attr(not(test), 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 //! # Working with EnumSets
22 //!
23 //! EnumSets can be constructed via [`EnumSet::new()`] like a normal set. In addition,
24 //! `#[derive(EnumSetType)]` creates operator overloads that allow you to create EnumSets like so:
25 //!
26 //! ```rust
27 //! # use enumset::*;
28 //! # #[derive(EnumSetType, Debug)] pub enum Enum { A, B, C, D, E, F, G }
29 //! let new_set = Enum::A | Enum::C | Enum::G;
30 //! assert_eq!(new_set.len(), 3);
31 //! ```
32 //!
33 //! All bitwise operations you would expect to work on bitsets also work on both EnumSets and
34 //! enums with `#[derive(EnumSetType)]`:
35 //! ```
36 //! # use enumset::*;
37 //! # #[derive(EnumSetType, Debug)] pub enum Enum { A, B, C, D, E, F, G }
38 //! // Intersection of sets
39 //! assert_eq!((Enum::A | Enum::B) & Enum::C, EnumSet::empty());
40 //! assert_eq!((Enum::A | Enum::B) & Enum::A, Enum::A);
41 //! assert_eq!(Enum::A & Enum::B, EnumSet::empty());
42 //!
43 //! // Symmetric difference of sets
44 //! assert_eq!((Enum::A | Enum::B) ^ (Enum::B | Enum::C), Enum::A | Enum::C);
45 //! assert_eq!(Enum::A ^ Enum::C, Enum::A | Enum::C);
46 //!
47 //! // Difference of sets
48 //! assert_eq!((Enum::A | Enum::B | Enum::C) - Enum::B, Enum::A | Enum::C);
49 //!
50 //! // Complement of sets
51 //! assert_eq!(!(Enum::E | Enum::G), Enum::A | Enum::B | Enum::C | Enum::D | Enum::F);
52 //! ```
53 //!
54 //! The [`enum_set!`] macro allows you to create EnumSets in constant contexts:
55 //!
56 //! ```rust
57 //! # use enumset::*;
58 //! # #[derive(EnumSetType, Debug)] pub enum Enum { A, B, C, D, E, F, G }
59 //! const CONST_SET: EnumSet<Enum> = enum_set!(Enum::A | Enum::B);
60 //! assert_eq!(CONST_SET, Enum::A | Enum::B);
61 //! ```
62 //!
63 //! Mutable operations on the [`EnumSet`] otherwise work basically as expected:
64 //!
65 //! ```rust
66 //! # use enumset::*;
67 //! # #[derive(EnumSetType, Debug)] pub enum Enum { A, B, C, D, E, F, G }
68 //! let mut set = EnumSet::new();
69 //! set.insert(Enum::A);
70 //! set.insert_all(Enum::E | Enum::G);
71 //! assert!(set.contains(Enum::A));
72 //! assert!(!set.contains(Enum::B));
73 //! assert_eq!(set, Enum::A | Enum::E | Enum::G);
74 //! ```
75
76 #[cfg(test)] extern crate core;
77 extern crate enumset_derive;
78 extern crate num_traits;
79 #[cfg(feature = "serde")] extern crate serde2 as serde;
80
81 pub use enumset_derive::*;
82 mod enumset { pub use super::*; }
83
84 use core::fmt;
85 use core::fmt::{Debug, Formatter};
86 use core::hash::Hash;
87 use core::ops::*;
88
89 use num_traits::*;
90
91 #[doc(hidden)]
92 /// Everything in this module is internal API and may change at any time.
93 pub mod internal {
94     use super::*;
95
96     /// A struct used to type check [`enum_set!`].
97     pub struct EnumSetSameTypeHack<'a, T: EnumSetType + 'static> {
98         pub unified: &'a [T],
99         pub enum_set: EnumSet<T>,
100     }
101
102     /// A reexport of core to allow our macros to be generic to std vs core.
103     pub extern crate core;
104
105     /// A reexport of serde so there is no requirement to depend on serde.
106     #[cfg(feature = "serde")] pub extern crate serde2 as serde;
107 }
108
109 mod private {
110     use super::*;
111     pub trait EnumSetTypeRepr : PrimInt + FromPrimitive + WrappingSub + CheckedShl + Debug + Hash {
112         const WIDTH: u8;
113     }
114     macro_rules! prim {
115         ($name:ty, $width:expr) => {
116             impl EnumSetTypeRepr for $name {
117                 const WIDTH: u8 = $width;
118             }
119         }
120     }
121     prim!(u8  , 8  );
122     prim!(u16 , 16 );
123     prim!(u32 , 32 );
124     prim!(u64 , 64 );
125     prim!(u128, 128);
126 }
127 use private::EnumSetTypeRepr;
128
129 /// The trait used to define enum types that may be used with [`EnumSet`].
130 ///
131 /// This trait should be implemented using `#[derive(EnumSetType)]`. Its internal structure is
132 /// not currently stable, and may change at any time.
133 ///
134 /// # Custom Derive
135 ///
136 /// The custom derive for `EnumSetType` automatically creates implementations of [`PartialEq`],
137 /// [`Sub`], [`BitAnd`], [`BitOr`], [`BitXor`], and [`Not`] allowing the enum to be used as
138 /// if it were an [`EnumSet`] in expressions. This can be disabled by adding an `#[enumset_no_ops]`
139 /// annotation to the enum.
140 ///
141 /// The custom derive for `EnumSetType` also automatically creates implementations equivalent to
142 /// `#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]`. This can be disabled by adding
143 /// an `#[enumset_no_derives]` annotation to the enum.
144 ///
145 /// Any C-like enum is supported, as long as there are no more than 128 variants in the enum,
146 /// and no variant discriminator is larger than 127.
147 ///
148 /// # Examples
149 ///
150 /// Deriving a plain EnumSetType:
151 ///
152 /// ```rust
153 /// # use enumset::*;
154 /// #[derive(EnumSetType, Debug)]
155 /// pub enum Enum {
156 ///    A, B, C, D, E, F, G,
157 /// }
158 /// ```
159 ///
160 /// Deriving a sparse EnumSetType:
161 ///
162 /// ```rust
163 /// # use enumset::*;
164 /// #[derive(EnumSetType, Debug)]
165 /// pub enum SparseEnum {
166 ///    A = 10, B = 20, C = 30, D = 127,
167 /// }
168 /// ```
169 ///
170 /// Deriving an EnumSetType without adding ops:
171 ///
172 /// ```rust
173 /// # use enumset::*;
174 /// #[derive(EnumSetType, Debug)]
175 /// #[enumset_no_ops]
176 /// pub enum NoOpsEnum {
177 ///    A, B, C, D, E, F, G,
178 /// }
179 /// ```
180 pub unsafe trait EnumSetType: Copy {
181     #[doc(hidden)] type Repr: EnumSetTypeRepr;
182     #[doc(hidden)] const ALL_BITS: Self::Repr;
183     #[doc(hidden)] fn enum_into_u8(self) -> u8;
184     #[doc(hidden)] unsafe fn enum_from_u8(val: u8) -> Self;
185
186     #[cfg(feature = "serde")] #[doc(hidden)]
187     fn serialize<S: serde::Serializer>(set: EnumSet<Self>, ser: S) -> Result<S::Ok, S::Error>;
188     #[cfg(feature = "serde")] #[doc(hidden)]
189     fn deserialize<'de, D: serde::Deserializer<'de>>(de: D) -> Result<EnumSet<Self>, D::Error>;
190 }
191
192 /// An efficient set type for enums.
193 #[derive(Copy, Clone, PartialOrd, Ord, PartialEq, Eq, Hash)]
194 pub struct EnumSet<T : EnumSetType> {
195     #[doc(hidden)]
196     /// This is public due to the [`enum_set!`] macro.
197     /// This is **NOT** public API and may change at any time.
198     pub __enumset_underlying: T::Repr
199 }
200 impl <T : EnumSetType> EnumSet<T> {
201     fn mask(bit: u8) -> T::Repr {
202         Shl::<usize>::shl(T::Repr::one(), bit as usize)
203     }
204     fn has_bit(&self, bit: u8) -> bool {
205         let mask = Self::mask(bit);
206         self.__enumset_underlying & mask == mask
207     }
208     fn partial_bits(bits: u8) -> T::Repr {
209         T::Repr::one().checked_shl(bits.into())
210             .unwrap_or(T::Repr::zero())
211             .wrapping_sub(&T::Repr::one())
212     }
213
214     // Returns all bits valid for the enum
215     fn all_bits() -> T::Repr {
216         T::ALL_BITS
217     }
218
219     /// Returns an empty set.
220     pub fn new() -> Self {
221         EnumSet { __enumset_underlying: T::Repr::zero() }
222     }
223
224     /// Returns a set containing a single value.
225     pub fn only(t: T) -> Self {
226         EnumSet { __enumset_underlying: Self::mask(t.enum_into_u8()) }
227     }
228
229     /// Returns an empty set.
230     pub fn empty() -> Self {
231         Self::new()
232     }
233     /// Returns a set with all bits set.
234     pub fn all() -> Self {
235         EnumSet { __enumset_underlying: Self::all_bits() }
236     }
237
238     /// Total number of bits this enumset uses. Note that the actual amount of space used is
239     /// rounded up to the next highest integer type (`u8`, `u16`, `u32`, `u64`, or `u128`).
240     ///
241     /// This is the same as [`EnumSet::variant_count`] except in enums with "sparse" variants.
242     /// (e.g. `enum Foo { A = 10, B = 20 }`)
243     pub fn bit_width() -> u8 {
244         T::Repr::WIDTH - T::ALL_BITS.leading_zeros() as u8
245     }
246
247     /// The number of valid variants in this enumset.
248     ///
249     /// This is the same as [`EnumSet::bit_width`] except in enums with "sparse" variants.
250     /// (e.g. `enum Foo { A = 10, B = 20 }`)
251     pub fn variant_count() -> u8 {
252         T::ALL_BITS.count_ones() as u8
253     }
254
255     /// Returns the raw bits of this set
256     pub fn to_bits(&self) -> u128 {
257         self.__enumset_underlying.to_u128()
258             .expect("Impossible: Bits cannot be to converted into i128?")
259     }
260
261     /// Constructs a bitset from raw bits.
262     ///
263     /// # Panics
264     /// If bits not in the enum are set.
265     pub fn from_bits(bits: u128) -> Self {
266         assert!((bits & !Self::all().to_bits()) == 0, "Bits not valid for the enum were set.");
267         EnumSet {
268             __enumset_underlying: T::Repr::from_u128(bits)
269                 .expect("Impossible: Valid bits too large to fit in repr?")
270         }
271     }
272
273     /// Returns the number of values in this set.
274     pub fn len(&self) -> usize {
275         self.__enumset_underlying.count_ones() as usize
276     }
277     /// Checks if the set is empty.
278     pub fn is_empty(&self) -> bool {
279         self.__enumset_underlying.is_zero()
280     }
281     /// Removes all elements from the set.
282     pub fn clear(&mut self) {
283         self.__enumset_underlying = T::Repr::zero()
284     }
285
286     /// Checks if this set shares no elements with another.
287     pub fn is_disjoint(&self, other: Self) -> bool {
288         (*self & other).is_empty()
289     }
290     /// Checks if all elements in another set are in this set.
291     pub fn is_superset(&self, other: Self) -> bool {
292         (*self & other).__enumset_underlying == other.__enumset_underlying
293     }
294     /// Checks if all elements of this set are in another set.
295     pub fn is_subset(&self, other: Self) -> bool {
296         other.is_superset(*self)
297     }
298
299     /// Returns a set containing the union of all elements in both sets.
300     pub fn union(&self, other: Self) -> Self {
301         EnumSet { __enumset_underlying: self.__enumset_underlying | other.__enumset_underlying }
302     }
303     /// Returns a set containing all elements in common with another set.
304     pub fn intersection(&self, other: Self) -> Self {
305         EnumSet { __enumset_underlying: self.__enumset_underlying & other.__enumset_underlying }
306     }
307     /// Returns a set with all elements of the other set removed.
308     pub fn difference(&self, other: Self) -> Self {
309         EnumSet { __enumset_underlying: self.__enumset_underlying & !other.__enumset_underlying }
310     }
311     /// Returns a set with all elements not contained in both sets.
312     pub fn symmetrical_difference(&self, other: Self) -> Self {
313         EnumSet { __enumset_underlying: self.__enumset_underlying ^ other.__enumset_underlying }
314     }
315     /// Returns a set containing all elements not in this set.
316     pub fn complement(&self) -> Self {
317         EnumSet { __enumset_underlying: !self.__enumset_underlying & Self::all_bits() }
318     }
319
320     /// Checks whether this set contains a value.
321     pub fn contains(&self, value: T) -> bool {
322         self.has_bit(value.enum_into_u8())
323     }
324
325     /// Adds a value to this set.
326     pub fn insert(&mut self, value: T) -> bool {
327         let contains = self.contains(value);
328         self.__enumset_underlying = self.__enumset_underlying | Self::mask(value.enum_into_u8());
329         contains
330     }
331     /// Removes a value from this set.
332     pub fn remove(&mut self, value: T) -> bool {
333         let contains = self.contains(value);
334         self.__enumset_underlying = self.__enumset_underlying & !Self::mask(value.enum_into_u8());
335         contains
336     }
337
338     /// Adds all elements in another set to this one.
339     pub fn insert_all(&mut self, other: Self) {
340         self.__enumset_underlying = self.__enumset_underlying | other.__enumset_underlying
341     }
342     /// Removes all values in another set from this one.
343     pub fn remove_all(&mut self, other: Self) {
344         self.__enumset_underlying = self.__enumset_underlying & !other.__enumset_underlying
345     }
346
347     /// Creates an iterator over the values in this set.
348     pub fn iter(&self) -> EnumSetIter<T> {
349         EnumSetIter(*self, 0)
350     }
351 }
352
353 impl <T: EnumSetType> Default for EnumSet<T> {
354     /// Returns an empty set.
355     fn default() -> Self {
356         Self::new()
357     }
358 }
359
360 impl <T : EnumSetType> IntoIterator for EnumSet<T> {
361     type Item = T;
362     type IntoIter = EnumSetIter<T>;
363
364     fn into_iter(self) -> Self::IntoIter {
365         self.iter()
366     }
367 }
368
369 impl <T : EnumSetType, O: Into<EnumSet<T>>> Sub<O> for EnumSet<T> {
370     type Output = Self;
371     fn sub(self, other: O) -> Self::Output {
372         self.difference(other.into())
373     }
374 }
375 impl <T : EnumSetType, O: Into<EnumSet<T>>> BitAnd<O> for EnumSet<T> {
376     type Output = Self;
377     fn bitand(self, other: O) -> Self::Output {
378         self.intersection(other.into())
379     }
380 }
381 impl <T : EnumSetType, O: Into<EnumSet<T>>> BitOr<O> for EnumSet<T> {
382     type Output = Self;
383     fn bitor(self, other: O) -> Self::Output {
384         self.union(other.into())
385     }
386 }
387 impl <T : EnumSetType, O: Into<EnumSet<T>>> BitXor<O> for EnumSet<T> {
388     type Output = Self;
389     fn bitxor(self, other: O) -> Self::Output {
390         self.symmetrical_difference(other.into())
391     }
392 }
393
394 impl <T : EnumSetType, O: Into<EnumSet<T>>> SubAssign<O> for EnumSet<T> {
395     fn sub_assign(&mut self, rhs: O) {
396         *self = *self - rhs;
397     }
398 }
399 impl <T : EnumSetType, O: Into<EnumSet<T>>> BitAndAssign<O> for EnumSet<T> {
400     fn bitand_assign(&mut self, rhs: O) {
401         *self = *self & rhs;
402     }
403 }
404 impl <T : EnumSetType, O: Into<EnumSet<T>>> BitOrAssign<O> for EnumSet<T> {
405     fn bitor_assign(&mut self, rhs: O) {
406         *self = *self | rhs;
407     }
408 }
409 impl <T : EnumSetType, O: Into<EnumSet<T>>> BitXorAssign<O> for EnumSet<T> {
410     fn bitxor_assign(&mut self, rhs: O) {
411         *self = *self ^ rhs;
412     }
413 }
414
415 impl <T : EnumSetType> Not for EnumSet<T> {
416     type Output = Self;
417     fn not(self) -> Self::Output {
418         self.complement()
419     }
420 }
421
422 impl <T : EnumSetType> From<T> for EnumSet<T> {
423     fn from(t: T) -> Self {
424         EnumSet::only(t)
425     }
426 }
427
428 impl <T : EnumSetType> PartialEq<T> for EnumSet<T> {
429     fn eq(&self, other: &T) -> bool {
430         self.__enumset_underlying == EnumSet::<T>::mask(other.enum_into_u8())
431     }
432 }
433 impl <T : EnumSetType + Debug> Debug for EnumSet<T> {
434     fn fmt(&self, f: &mut Formatter) -> fmt::Result {
435         let mut is_first = true;
436         f.write_str("EnumSet(")?;
437         for v in self.iter() {
438             if !is_first { f.write_str(" | ")?; }
439             is_first = false;
440             v.fmt(f)?;
441         }
442         f.write_str(")")?;
443         Ok(())
444     }
445 }
446
447 #[cfg(feature = "serde")]
448 impl <T : EnumSetType> serde::Serialize for EnumSet<T> {
449     fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
450         T::serialize(*self, serializer)
451     }
452 }
453
454 #[cfg(feature = "serde")]
455 impl <'de, T : EnumSetType> serde::Deserialize<'de> for EnumSet<T> {
456     fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
457         T::deserialize(deserializer)
458     }
459 }
460
461 /// The iterator used by [`EnumSet`](./struct.EnumSet.html).
462 #[derive(Copy, Clone, PartialOrd, Ord, PartialEq, Eq, Hash, Debug)]
463 pub struct EnumSetIter<T : EnumSetType>(EnumSet<T>, u8);
464 impl <T : EnumSetType> Iterator for EnumSetIter<T> {
465     type Item = T;
466
467     fn next(&mut self) -> Option<Self::Item> {
468         while self.1 < EnumSet::<T>::bit_width() {
469             let bit = self.1;
470             self.1 += 1;
471             if self.0.has_bit(bit) {
472                 return unsafe { Some(T::enum_from_u8(bit)) }
473             }
474         }
475         None
476     }
477     fn size_hint(&self) -> (usize, Option<usize>) {
478         let left_mask = EnumSet::<T>::partial_bits(self.1);
479         let left = (self.0.__enumset_underlying & left_mask).count_ones() as usize;
480         (left, Some(left))
481     }
482 }
483
484 /// Defines enums which can be used with EnumSet.
485 ///
486 /// [`Copy`], [`Clone`], [`PartialOrd`], [`Ord`], [`PartialEq`], [`Eq`], [`Hash`], [`Debug`],
487 /// [`Sub`], [`BitAnd`], [`BitOr`], [`BitXor`], and [`Not`] are automatically derived for the enum.
488 ///
489 /// These impls, in general, behave as if the enum variant was an [`EnumSet`] with a single value,
490 /// as those created by [`EnumSet::only`].
491 #[macro_export]
492 #[deprecated(since = "0.3.13", note = "Use `#[derive(EnumSetType)] instead.")]
493 macro_rules! enum_set_type {
494     ($(#[$enum_attr:meta])* $vis:vis enum $enum_name:ident {
495         $($(#[$attr:meta])* $variant:ident),* $(,)*
496     } $($rest:tt)*) => {
497         $(#[$enum_attr])* #[repr(u8)]
498         #[derive($crate::EnumSetType, Debug)]
499         $vis enum $enum_name {
500             $($(#[$attr])* $variant,)*
501         }
502
503         enum_set_type!($($rest)*);
504     };
505     () => { };
506 }
507
508 /// Creates a EnumSet literal, which can be used in const contexts.
509 ///
510 /// The syntax used is `enum_set!(Type::A | Type::B | Type::C)`. Each variant must be of the same
511 /// type, or a error will occur at compile-time.
512 ///
513 /// You may also explicitly state the type of the variants that follow, as in
514 /// `enum_set!(Type, Type::A | Type::B | Type::C)`.
515 ///
516 /// # Examples
517 ///
518 /// ```rust
519 /// # use enumset::*;
520 /// # #[derive(EnumSetType, Debug)] enum Enum { A, B, C }
521 /// const CONST_SET: EnumSet<Enum> = enum_set!(Enum::A | Enum::B);
522 /// assert_eq!(CONST_SET, Enum::A | Enum::B);
523 ///
524 /// const EXPLICIT_CONST_SET: EnumSet<Enum> = enum_set!(Enum, Enum::A | Enum::B);
525 /// assert_eq!(EXPLICIT_CONST_SET, Enum::A | Enum::B);
526 /// ```
527 ///
528 /// This macro is strongly typed. For example, the following will not compile:
529 ///
530 /// ```compile_fail
531 /// # use enumset::*;
532 /// # #[derive(EnumSetType, Debug)] enum Enum { A, B, C }
533 /// # #[derive(EnumSetType, Debug)] enum Enum2 { A, B, C }
534 /// let type_error = enum_set!(Enum::A | Enum2::B);
535 /// ```
536 #[macro_export]
537 macro_rules! enum_set {
538     () => {
539         $crate::EnumSet { __enumset_underlying: 0 }
540     };
541     ($($value:path)|* $(|)*) => {
542         $crate::internal::EnumSetSameTypeHack {
543             unified: &[$($value,)*],
544             enum_set: $crate::EnumSet {
545                 __enumset_underlying: 0 $(| (1 << ($value as u8)))*
546             },
547         }.enum_set
548     };
549     ($enum_name:ty, $($value:path)|* $(|)*) => {
550         $crate::EnumSet::<$enum_name> {
551             __enumset_underlying: 0 $(| (1 << ($value as $enum_name as u8)))*
552         }
553     }
554 }
555
556 #[cfg(test)]
557 #[allow(dead_code)]
558 mod test {
559     use super::*;
560
561     #[cfg(feature = "serde")]
562     extern crate bincode;
563
564     mod enums {
565         #[derive(::EnumSetType, Debug)]
566         pub enum SmallEnum {
567             A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, Z,
568         }
569         #[derive(::EnumSetType, Debug)]
570         pub enum LargeEnum {
571             _00,  _01,  _02,  _03,  _04,  _05,  _06,  _07,
572             _10,  _11,  _12,  _13,  _14,  _15,  _16,  _17,
573             _20,  _21,  _22,  _23,  _24,  _25,  _26,  _27,
574             _30,  _31,  _32,  _33,  _34,  _35,  _36,  _37,
575             _40,  _41,  _42,  _43,  _44,  _45,  _46,  _47,
576             _50,  _51,  _52,  _53,  _54,  _55,  _56,  _57,
577             _60,  _61,  _62,  _63,  _64,  _65,  _66,  _67,
578             _70,  _71,  _72,  _73,  _74,  _75,  _76,  _77,
579             A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, Z,
580         }
581         #[derive(::EnumSetType, Debug)]
582         pub enum Enum8 {
583             A, B, C, D, E, F, G, H,
584         }
585         #[derive(::EnumSetType, Debug)]
586         pub enum Enum128 {
587             A, B, C, D, E, F, G, H, _8, _9, _10, _11, _12, _13, _14, _15,
588             _16, _17, _18, _19, _20, _21, _22, _23, _24, _25, _26, _27, _28, _29, _30, _31,
589             _32, _33, _34, _35, _36, _37, _38, _39, _40, _41, _42, _43, _44, _45, _46, _47,
590             _48, _49, _50, _51, _52, _53, _54, _55, _56, _57, _58, _59, _60, _61, _62, _63,
591             _64, _65, _66, _67, _68, _69, _70, _71, _72, _73, _74, _75, _76, _77, _78, _79,
592             _80, _81, _82, _83, _84, _85, _86, _87, _88, _89, _90, _91, _92, _93, _94, _95,
593             _96, _97, _98, _99, _100, _101, _102, _103, _104, _105, _106, _107, _108, _109,
594             _110, _111, _112, _113, _114, _115, _116, _117, _118, _119, _120, _121, _122,
595             _123, _124,  _125, _126, _127,
596         }
597         #[derive(::EnumSetType, Debug)]
598         pub enum SparseEnum {
599             A = 10, B = 20, C = 30, D = 40, E = 50, F = 60, G = 70, H = 80,
600         }
601     }
602     use self::enums::*;
603
604     macro_rules! test_variants {
605         ($enum_name:ident $all_empty_test:ident $($variant:ident,)*) => {
606             #[test]
607             fn $all_empty_test() {
608                 let all = EnumSet::<$enum_name>::all();
609                 let empty = EnumSet::<$enum_name>::empty();
610
611                 $(
612                     assert!(!empty.contains($enum_name::$variant));
613                     assert!(all.contains($enum_name::$variant));
614                 )*
615             }
616         }
617     }
618     test_variants! { SmallEnum small_enum_all_empty
619         A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, Z,
620     }
621     test_variants! { LargeEnum large_enum_all_empty
622         _00,  _01,  _02,  _03,  _04,  _05,  _06,  _07,
623         _10,  _11,  _12,  _13,  _14,  _15,  _16,  _17,
624         _20,  _21,  _22,  _23,  _24,  _25,  _26,  _27,
625         _30,  _31,  _32,  _33,  _34,  _35,  _36,  _37,
626         _40,  _41,  _42,  _43,  _44,  _45,  _46,  _47,
627         _50,  _51,  _52,  _53,  _54,  _55,  _56,  _57,
628         _60,  _61,  _62,  _63,  _64,  _65,  _66,  _67,
629         _70,  _71,  _72,  _73,  _74,  _75,  _76,  _77,
630         A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, Z,
631     }
632     test_variants! { SparseEnum sparse_enum_all_empty
633         A, B, C, D, E, F, G,
634     }
635
636     macro_rules! test_enum {
637         ($e:ident, $m:ident) => {
638             mod $m {
639                 use super::*;
640
641                 const CONST_SET: EnumSet<$e> = enum_set!($e, $e::A | $e::C);
642                 const EMPTY_SET: EnumSet<$e> = enum_set!();
643                 #[test]
644                 fn const_set() {
645                     assert_eq!(CONST_SET.len(), 2);
646                     assert!(CONST_SET.contains($e::A));
647                     assert!(CONST_SET.contains($e::C));
648                     assert!(EMPTY_SET.is_empty());
649                 }
650
651                 #[test]
652                 fn basic_add_remove() {
653                     let mut set = EnumSet::new();
654                     set.insert($e::A);
655                     set.insert($e::B);
656                     set.insert($e::C);
657                     assert_eq!(set, $e::A | $e::B | $e::C);
658                     set.remove($e::B);
659                     assert_eq!(set, $e::A | $e::C);
660                     set.insert($e::D);
661                     assert_eq!(set, $e::A | $e::C | $e::D);
662                     set.insert_all($e::F | $e::E | $e::G);
663                     assert_eq!(set, $e::A | $e::C | $e::D | $e::F | $e::E | $e::G);
664                     set.remove_all($e::A | $e::D | $e::G);
665                     assert_eq!(set, $e::C | $e::F | $e::E);
666                     assert!(!set.is_empty());
667                     set.clear();
668                     assert!(set.is_empty());
669                 }
670
671                 #[test]
672                 fn empty_is_empty() {
673                     assert_eq!(EnumSet::<$e>::empty().len(), 0)
674                 }
675
676                 #[test]
677                 fn all_len() {
678                     assert_eq!(EnumSet::<$e>::all().len(), EnumSet::<$e>::variant_count() as usize)
679                 }
680
681                 #[test]
682                 fn basic_iter_test() {
683                     let mut set = EnumSet::new();
684                     set.insert($e::A);
685                     set.insert($e::B);
686                     set.insert($e::C);
687                     set.insert($e::E);
688
689                     let mut set_2 = EnumSet::new();
690                     let vec: Vec<$e> = set.iter().collect();
691                     for val in vec {
692                         assert!(!set_2.contains(val));
693                         set_2.insert(val);
694                     }
695                     assert_eq!(set, set_2);
696
697                     let mut set_3 = EnumSet::new();
698                     for val in set {
699                         assert!(!set_3.contains(val));
700                         set_3.insert(val);
701                     }
702                     assert_eq!(set, set_3);
703                 }
704
705                 #[test]
706                 fn basic_ops_test() {
707                     assert_eq!(($e::A | $e::B) | ($e::B | $e::C), $e::A | $e::B | $e::C);
708                     assert_eq!(($e::A | $e::B) & ($e::B | $e::C), $e::B);
709                     assert_eq!(($e::A | $e::B) ^ ($e::B | $e::C), $e::A | $e::C);
710                     assert_eq!(($e::A | $e::B) - ($e::B | $e::C), $e::A);
711                 }
712
713                 #[test]
714                 fn basic_set_status() {
715                     assert!(($e::A | $e::B | $e::C).is_disjoint($e::D | $e::E | $e::F));
716                     assert!(!($e::A | $e::B | $e::C | $e::D).is_disjoint($e::D | $e::E | $e::F));
717                     assert!(($e::A | $e::B).is_subset($e::A | $e::B | $e::C));
718                     assert!(!($e::A | $e::D).is_subset($e::A | $e::B | $e::C));
719                 }
720
721                 #[test]
722                 fn debug_impl() {
723                     assert_eq!(format!("{:?}", $e::A | $e::B | $e::D), "EnumSet(A | B | D)");
724                 }
725
726                 #[test]
727                 fn to_from_bits() {
728                     let value = $e::A | $e::C | $e::D | $e::F | $e::E | $e::G;
729                     assert_eq!(EnumSet::from_bits(value.to_bits()), value);
730                 }
731
732                 #[test]
733                 #[should_panic]
734                 fn too_many_bits() {
735                     if EnumSet::<$e>::variant_count() == 128 {
736                         panic!("(test skipped)")
737                     }
738                     EnumSet::<$e>::from_bits(!0);
739                 }
740
741                 #[test]
742                 fn match_const_test() {
743                     match CONST_SET {
744                         CONST_SET => { /* ok */ }
745                         _ => panic!("match fell through?"),
746                     }
747                 }
748
749                 #[test]
750                 #[cfg(feature = "serde")]
751                 fn serialize_deserialize_test() {
752                     let value = $e::A | $e::C | $e::D | $e::F | $e::E | $e::G;
753                     let serialized = bincode::serialize(&value).unwrap();
754                     let deserialized = bincode::deserialize::<EnumSet<$e>>(&serialized).unwrap();
755                     assert_eq!(value, deserialized);
756                 }
757             }
758         }
759     }
760
761     test_enum!(SmallEnum, small_enum);
762     test_enum!(LargeEnum, large_enum);
763     test_enum!(Enum8, enum8);
764     test_enum!(Enum128, enum128);
765     test_enum!(SparseEnum, sparse_enum);
766 }