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