]> git.lizzy.rs Git - enumset.git/blobdiff - enumset/src/lib.rs
use trailing zeros count for iteration
[enumset.git] / enumset / src / lib.rs
index 679b4700650cbf858cf01d8168b1967d7a20b970..98c7977688f6c1b4af9d06b68b0eee7b04503c5a 100644 (file)
@@ -1,9 +1,11 @@
-#![cfg_attr(not(test), no_std)]
+#![no_std]
 #![forbid(missing_docs)]
 
 //! A library for defining enums that can be used in compact bit sets. It supports enums up to 128
 //! variants, and has a macro to use these sets in constants.
 //!
+//! For serde support, enable the `serde` feature.
+//!
 //! # Defining enums for use with EnumSet
 //!
 //! Enums to be used with [`EnumSet`] should be defined using `#[derive(EnumSetType)]`:
@@ -16,6 +18,8 @@
 //! }
 //! ```
 //!
+//! For more information on more advanced use cases, see the documentation for [`EnumSetType`].
+//!
 //! # Working with EnumSets
 //!
 //! EnumSets can be constructed via [`EnumSet::new()`] like a normal set. In addition,
@@ -30,7 +34,7 @@
 //!
 //! All bitwise operations you would expect to work on bitsets also work on both EnumSets and
 //! enums with `#[derive(EnumSetType)]`:
-//! ```
+//! ```rust
 //! # use enumset::*;
 //! # #[derive(EnumSetType, Debug)] pub enum Enum { A, B, C, D, E, F, G }
 //! // Intersection of sets
@@ -58,7 +62,7 @@
 //! assert_eq!(CONST_SET, Enum::A | Enum::B);
 //! ```
 //!
-//! Mutable operations on the [`EnumSet`] otherwise work basically as expected:
+//! Mutable operations on the [`EnumSet`] otherwise similarly to Rust's builtin sets:
 //!
 //! ```rust
 //! # use enumset::*;
 //! assert_eq!(set, Enum::A | Enum::E | Enum::G);
 //! ```
 
-#[cfg(test)] extern crate core;
-extern crate enumset_derive;
-extern crate num_traits;
-
-pub use enumset_derive::*;
-mod enumset { pub use super::*; }
+pub use enumset_derive::EnumSetType;
 
+use core::cmp::Ordering;
 use core::fmt;
 use core::fmt::{Debug, Formatter};
-use core::hash::Hash;
+use core::hash::{Hash, Hasher};
+use core::iter::{FromIterator, Sum};
 use core::ops::*;
 
-use num_traits::*;
-
 #[doc(hidden)]
 /// Everything in this module is internal API and may change at any time.
-pub mod internal {
+pub mod __internal {
     use super::*;
 
-    #[doc(hidden)]
-    /// A struct used to type check [`enum_set!`].
-    pub struct EnumSetSameTypeHack<'a, T: EnumSetType + 'static> {
-        pub unified: &'a [T],
-        pub enum_set: EnumSet<T>,
-    }
-
     /// A reexport of core to allow our macros to be generic to std vs core.
-    pub extern crate core;
-}
-
-mod private {
-    use super::*;
-    pub trait EnumSetTypeRepr : PrimInt + FromPrimitive + WrappingSub + CheckedShl + Debug + Hash {
-        const WIDTH: u8;
+    pub use ::core as core_export;
+
+    /// A reexport of serde so there is no requirement to depend on serde.
+    #[cfg(feature = "serde")] pub use serde2 as serde;
+
+    /// The actual members of EnumSetType. Put here to avoid polluting global namespaces.
+    pub unsafe trait EnumSetTypePrivate {
+        /// The underlying type used to store the bitset.
+        type Repr: EnumSetTypeRepr;
+        /// A mask of bits that are valid in the bitset.
+        const ALL_BITS: Self::Repr;
+
+        /// Converts an enum of this type into its bit position.
+        fn enum_into_u32(self) -> u32;
+        /// Converts a bit position into an enum value.
+        unsafe fn enum_from_u32(val: u32) -> Self;
+
+        /// Serializes the `EnumSet`.
+        ///
+        /// This and `deserialize` are part of the `EnumSetType` trait so the procedural derive
+        /// can control how `EnumSet` is serialized.
+        #[cfg(feature = "serde")]
+        fn serialize<S: serde::Serializer>(set: EnumSet<Self>, ser: S) -> Result<S::Ok, S::Error>
+            where Self: EnumSetType;
+        /// Deserializes the `EnumSet`.
+        #[cfg(feature = "serde")]
+        fn deserialize<'de, D: serde::Deserializer<'de>>(de: D) -> Result<EnumSet<Self>, D::Error>
+            where Self: EnumSetType;
     }
-    macro_rules! prim {
-        ($name:ty, $width:expr) => {
-            impl EnumSetTypeRepr for $name {
-                const WIDTH: u8 = $width;
-            }
-        }
-    }
-    prim!(u8  , 8  );
-    prim!(u16 , 16 );
-    prim!(u32 , 32 );
-    prim!(u64 , 64 );
-    prim!(u128, 128);
 }
-use private::EnumSetTypeRepr;
+use crate::__internal::EnumSetTypePrivate;
+#[cfg(feature = "serde")] use crate::__internal::serde;
+#[cfg(feature = "serde")] use crate::serde::{Serialize, Deserialize};
+
+mod repr;
+use crate::repr::EnumSetTypeRepr;
 
 /// The trait used to define enum types that may be used with [`EnumSet`].
 ///
 /// This trait should be implemented using `#[derive(EnumSetType)]`. Its internal structure is
-/// not currently stable, and may change at any time.
+/// not stable, and may change at any time.
 ///
 /// # Custom Derive
 ///
-/// The custom derive for `EnumSetType` automatically creates implementations of [`PartialEq`],
+/// Any C-like enum is supported, as long as there are no more than 128 variants in the enum,
+/// and no variant discriminator is larger than 127.
+///
+/// The custom derive for [`EnumSetType`] automatically creates implementations of [`PartialEq`],
 /// [`Sub`], [`BitAnd`], [`BitOr`], [`BitXor`], and [`Not`] allowing the enum to be used as
-/// if it were an [`EnumSet`] in expressions. This can be disabled by adding an `#[enumset_no_ops]`
+/// if it were an [`EnumSet`] in expressions. This can be disabled by adding an `#[enumset(no_ops)]`
 /// annotation to the enum.
 ///
-/// The custom derive for `EnumSetType` also automatically creates implementations equivalent to
-/// `#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]`. This can be disabled by adding
-/// an `#[enumset_no_derives]` annotation to the enum.
+/// The custom derive for `EnumSetType` automatically implements [`Copy`], [`Clone`], [`Eq`], and
+/// [`PartialEq`] on the enum. These are required for the [`EnumSet`] to function.
 ///
-/// Any C-like enum is supported, as long as there are no more than 128 variants in the enum,
-/// and no variant discriminator is larger than 127.
+/// In addition, if you have renamed the `enumset` crate in your crate, you can use the
+/// `#[enumset(crate_name = "enumset2")]` attribute to tell the custom derive to use that name
+/// instead.
+///
+/// Attributes controlling the serialization of an `EnumSet` are documented in
+/// [its documentation](./struct.EnumSet.html#serialization).
 ///
 /// # Examples
 ///
@@ -146,7 +158,7 @@ use private::EnumSetTypeRepr;
 ///
 /// ```rust
 /// # use enumset::*;
-/// #[derive(EnumSetType, Debug)]
+/// #[derive(EnumSetType)]
 /// pub enum Enum {
 ///    A, B, C, D, E, F, G,
 /// }
@@ -156,7 +168,7 @@ use private::EnumSetTypeRepr;
 ///
 /// ```rust
 /// # use enumset::*;
-/// #[derive(EnumSetType, Debug)]
+/// #[derive(EnumSetType)]
 /// pub enum SparseEnum {
 ///    A = 10, B = 20, C = 30, D = 127,
 /// }
@@ -166,180 +178,284 @@ use private::EnumSetTypeRepr;
 ///
 /// ```rust
 /// # use enumset::*;
-/// #[derive(EnumSetType, Debug)]
-/// #[enumset_no_ops]
+/// #[derive(EnumSetType)]
+/// #[enumset(no_ops)]
 /// pub enum NoOpsEnum {
 ///    A, B, C, D, E, F, G,
 /// }
 /// ```
-pub unsafe trait EnumSetType: Copy {
-    #[doc(hidden)] type Repr: EnumSetTypeRepr;
-    #[doc(hidden)] const ALL_BITS: Self::Repr;
-    #[doc(hidden)] fn enum_into_u8(self) -> u8;
-    #[doc(hidden)] unsafe fn enum_from_u8(val: u8) -> Self;
-}
+pub unsafe trait EnumSetType: Copy + Eq + EnumSetTypePrivate { }
 
 /// An efficient set type for enums.
-#[derive(Copy, Clone, PartialOrd, Ord, PartialEq, Eq, Hash)]
-pub struct EnumSet<T : EnumSetType> {
+///
+/// It is implemented using a bitset stored using the smallest integer that can fit all bits
+/// in the underlying enum. In general, an enum variant with a numeric value of `n` is stored in
+/// the nth least significant bit (corresponding with a mask of, e.g. `1 << enum as u32`).
+///
+/// # Serialization
+///
+/// When the `serde` feature is enabled, `EnumSet`s can be serialized and deserialized using
+/// the `serde` crate. The exact serialization format can be controlled with additional attributes
+/// on the enum type. These attributes are valid regardless of whether the `serde` feature
+/// is enabled.
+///
+/// By default, `EnumSet`s serialize by directly writing out the underlying bitset as an integer
+/// of the smallest type that can fit in the underlying enum. You can add a
+/// `#[enumset(serialize_repr = "u8")]` attribute to your enum to control the integer type used
+/// for serialization. This can be important for avoiding unintentional breaking changes when
+/// `EnumSet`s are serialized with formats like `bincode`.
+///
+/// By default, unknown bits are ignored and silently removed from the bitset. To override this
+/// behavior, you can add a `#[enumset(serialize_deny_unknown)]` attribute. This will cause
+/// deserialization to fail if an invalid bit is set.
+///
+/// In addition, the `#[enumset(serialize_as_list)]` attribute causes the `EnumSet` to be
+/// instead serialized as a list of enum variants. This requires your enum type implement
+/// [`Serialize`] and [`Deserialize`]. Note that this is a breaking change
+#[derive(Copy, Clone, PartialEq, Eq)]
+#[repr(transparent)]
+pub struct EnumSet<T: EnumSetType> {
     #[doc(hidden)]
     /// This is public due to the [`enum_set!`] macro.
     /// This is **NOT** public API and may change at any time.
-    pub __enumset_underlying: T::Repr
+    pub __priv_repr: T::Repr
 }
-impl <T : EnumSetType> EnumSet<T> {
-    fn mask(bit: u8) -> T::Repr {
-        Shl::<usize>::shl(T::Repr::one(), bit as usize)
-    }
-    fn has_bit(&self, bit: u8) -> bool {
-        let mask = Self::mask(bit);
-        self.__enumset_underlying & mask == mask
-    }
-    fn partial_bits(bits: u8) -> T::Repr {
-        T::Repr::one().checked_shl(bits.into())
-            .unwrap_or(T::Repr::zero())
-            .wrapping_sub(&T::Repr::one())
-    }
-
+impl <T: EnumSetType> EnumSet<T> {
     // Returns all bits valid for the enum
     fn all_bits() -> T::Repr {
         T::ALL_BITS
     }
 
-    /// Returns an empty set.
+    /// Creates an empty `EnumSet`.
     pub fn new() -> Self {
-        EnumSet { __enumset_underlying: T::Repr::zero() }
+        EnumSet { __priv_repr: T::Repr::empty() }
     }
 
-    /// Returns a set containing a single value.
+    /// Returns an `EnumSet` containing a single element.
     pub fn only(t: T) -> Self {
-        EnumSet { __enumset_underlying: Self::mask(t.enum_into_u8()) }
+        let mut set = Self::new();
+        set.insert(t);
+        set
     }
 
-    /// Returns an empty set.
+    /// Creates an empty `EnumSet`.
+    ///
+    /// This is an alias for [`EnumSet::new`].
     pub fn empty() -> Self {
         Self::new()
     }
-    /// Returns a set with all bits set.
+
+    /// Returns an `EnumSet` containing all valid variants of the enum.
     pub fn all() -> Self {
-        EnumSet { __enumset_underlying: Self::all_bits() }
+        EnumSet { __priv_repr: Self::all_bits() }
     }
 
-    /// Total number of bits this enumset uses. Note that the actual amount of space used is
+    /// Total number of bits used by this type. Note that the actual amount of space used is
     /// rounded up to the next highest integer type (`u8`, `u16`, `u32`, `u64`, or `u128`).
     ///
     /// This is the same as [`EnumSet::variant_count`] except in enums with "sparse" variants.
     /// (e.g. `enum Foo { A = 10, B = 20 }`)
-    pub fn bit_width() -> u8 {
-        T::Repr::WIDTH - T::ALL_BITS.leading_zeros() as u8
+    pub fn bit_width() -> u32 {
+        T::Repr::WIDTH - T::ALL_BITS.leading_zeros()
     }
 
-    /// The number of valid variants in this enumset.
+    /// The number of valid variants that this type can contain.
     ///
     /// This is the same as [`EnumSet::bit_width`] except in enums with "sparse" variants.
     /// (e.g. `enum Foo { A = 10, B = 20 }`)
-    pub fn variant_count() -> u8 {
-        T::ALL_BITS.count_ones() as u8
-    }
-
-    /// Returns the raw bits of this set
-    pub fn to_bits(&self) -> u128 {
-        self.__enumset_underlying.to_u128()
-            .expect("Impossible: Bits cannot be to converted into i128?")
-    }
-
-    /// Constructs a bitset from raw bits.
-    ///
-    /// # Panics
-    /// If bits not in the enum are set.
-    pub fn from_bits(bits: u128) -> Self {
-        assert!((bits & !Self::all().to_bits()) == 0, "Bits not valid for the enum were set.");
-        EnumSet {
-            __enumset_underlying: T::Repr::from_u128(bits)
-                .expect("Impossible: Valid bits too large to fit in repr?")
-        }
+    pub fn variant_count() -> u32 {
+        T::ALL_BITS.count_ones()
     }
 
-    /// Returns the number of values in this set.
+    /// Returns the number of elements in this set.
     pub fn len(&self) -> usize {
-        self.__enumset_underlying.count_ones() as usize
+        self.__priv_repr.count_ones() as usize
     }
-    /// Checks if the set is empty.
+    /// Returns `true` if the set contains no elements.
     pub fn is_empty(&self) -> bool {
-        self.__enumset_underlying.is_zero()
+        self.__priv_repr.is_empty()
     }
     /// Removes all elements from the set.
     pub fn clear(&mut self) {
-        self.__enumset_underlying = T::Repr::zero()
+        self.__priv_repr = T::Repr::empty()
     }
 
-    /// Checks if this set shares no elements with another.
+    /// Returns `true` if `self` has no elements in common with `other`. This is equivalent to
+    /// checking for an empty intersection.
     pub fn is_disjoint(&self, other: Self) -> bool {
         (*self & other).is_empty()
     }
-    /// Checks if all elements in another set are in this set.
+    /// Returns `true` if the set is a superset of another, i.e., `self` contains at least all the
+    /// values in `other`.
     pub fn is_superset(&self, other: Self) -> bool {
-        (*self & other).__enumset_underlying == other.__enumset_underlying
+        (*self & other).__priv_repr == other.__priv_repr
     }
-    /// Checks if all elements of this set are in another set.
+    /// Returns `true` if the set is a subset of another, i.e., `other` contains at least all
+    /// the values in `self`.
     pub fn is_subset(&self, other: Self) -> bool {
         other.is_superset(*self)
     }
 
-    /// Returns a set containing the union of all elements in both sets.
+    /// Returns a set containing any elements present in either set.
     pub fn union(&self, other: Self) -> Self {
-        EnumSet { __enumset_underlying: self.__enumset_underlying | other.__enumset_underlying }
+        EnumSet { __priv_repr: self.__priv_repr | other.__priv_repr }
     }
-    /// Returns a set containing all elements in common with another set.
+    /// Returns a set containing every element present in both sets.
     pub fn intersection(&self, other: Self) -> Self {
-        EnumSet { __enumset_underlying: self.__enumset_underlying & other.__enumset_underlying }
+        EnumSet { __priv_repr: self.__priv_repr & other.__priv_repr }
     }
-    /// Returns a set with all elements of the other set removed.
+    /// Returns a set containing element present in `self` but not in `other`.
     pub fn difference(&self, other: Self) -> Self {
-        EnumSet { __enumset_underlying: self.__enumset_underlying & !other.__enumset_underlying }
+        EnumSet { __priv_repr: self.__priv_repr.and_not(other.__priv_repr) }
     }
-    /// Returns a set with all elements not contained in both sets.
+    /// Returns a set containing every element present in either `self` or `other`, but is not
+    /// present in both.
     pub fn symmetrical_difference(&self, other: Self) -> Self {
-        EnumSet { __enumset_underlying: self.__enumset_underlying ^ other.__enumset_underlying }
+        EnumSet { __priv_repr: self.__priv_repr ^ other.__priv_repr }
     }
-    /// Returns a set containing all elements not in this set.
+    /// Returns a set containing all enum variants not in this set.
     pub fn complement(&self) -> Self {
-        EnumSet { __enumset_underlying: !self.__enumset_underlying & Self::all_bits() }
+        EnumSet { __priv_repr: !self.__priv_repr & Self::all_bits() }
     }
 
     /// Checks whether this set contains a value.
     pub fn contains(&self, value: T) -> bool {
-        self.has_bit(value.enum_into_u8())
+        self.__priv_repr.has_bit(value.enum_into_u32())
     }
 
     /// Adds a value to this set.
+    ///
+    /// If the set did not have this value present, `true` is returned.
+    ///
+    /// If the set did have this value present, `false` is returned.
     pub fn insert(&mut self, value: T) -> bool {
-        let contains = self.contains(value);
-        self.__enumset_underlying = self.__enumset_underlying | Self::mask(value.enum_into_u8());
+        let contains = !self.contains(value);
+        self.__priv_repr.add_bit(value.enum_into_u32());
         contains
     }
-    /// Removes a value from this set.
+    /// Removes a value from this set. Returns whether the value was present in the set.
     pub fn remove(&mut self, value: T) -> bool {
         let contains = self.contains(value);
-        self.__enumset_underlying = self.__enumset_underlying & !Self::mask(value.enum_into_u8());
+        self.__priv_repr.remove_bit(value.enum_into_u32());
         contains
     }
 
     /// Adds all elements in another set to this one.
     pub fn insert_all(&mut self, other: Self) {
-        self.__enumset_underlying = self.__enumset_underlying | other.__enumset_underlying
+        self.__priv_repr = self.__priv_repr | other.__priv_repr
     }
     /// Removes all values in another set from this one.
     pub fn remove_all(&mut self, other: Self) {
-        self.__enumset_underlying = self.__enumset_underlying & !other.__enumset_underlying
+        self.__priv_repr = self.__priv_repr.and_not(other.__priv_repr);
     }
 
     /// Creates an iterator over the values in this set.
+    ///
+    /// Note that iterator invalidation is impossible as the iterator contains a copy of this type,
+    /// rather than holding a reference to it.
     pub fn iter(&self) -> EnumSetIter<T> {
-        EnumSetIter(*self, 0)
+        EnumSetIter(*self)
+    }
+}
+
+/// Helper macro for generating conversion functions.
+macro_rules! conversion_impls {
+    (
+        $(for_num!(
+            $underlying:ty, $underlying_str:expr,
+            $from_fn:ident $to_fn:ident $from_fn_opt:ident $to_fn_opt:ident,
+            $from:ident $try_from:ident $from_truncated:ident
+            $to:ident $try_to:ident $to_truncated:ident
+        );)*
+    ) => {
+        impl <T : EnumSetType> EnumSet<T> {$(
+            #[doc = "Returns a `"]
+            #[doc = $underlying_str]
+            #[doc = "` representing the elements of this set.\n\nIf the underlying bitset will \
+                     not fit in a `"]
+            #[doc = $underlying_str]
+            #[doc = "`, this method will panic."]
+            pub fn $to(&self) -> $underlying {
+                self.$try_to().expect("Bitset will not fit into this type.")
+            }
+
+            #[doc = "Tries to return a `"]
+            #[doc = $underlying_str]
+            #[doc = "` representing the elements of this set.\n\nIf the underlying bitset will \
+                     not fit in a `"]
+            #[doc = $underlying_str]
+            #[doc = "`, this method will instead return `None`."]
+            pub fn $try_to(&self) -> Option<$underlying> {
+                EnumSetTypeRepr::$to_fn_opt(&self.__priv_repr)
+            }
+
+            #[doc = "Returns a truncated `"]
+            #[doc = $underlying_str]
+            #[doc = "` representing the elements of this set.\n\nIf the underlying bitset will \
+                     not fit in a `"]
+            #[doc = $underlying_str]
+            #[doc = "`, this method will truncate any bits that don't fit."]
+            pub fn $to_truncated(&self) -> $underlying {
+                EnumSetTypeRepr::$to_fn(&self.__priv_repr)
+            }
+
+            #[doc = "Constructs a bitset from a `"]
+            #[doc = $underlying_str]
+            #[doc = "`.\n\nIf a bit that doesn't correspond to an enum variant is set, this \
+                     method will panic."]
+            pub fn $from(bits: $underlying) -> Self {
+                Self::$try_from(bits).expect("Bitset contains invalid variants.")
+            }
+
+            #[doc = "Attempts to constructs a bitset from a `"]
+            #[doc = $underlying_str]
+            #[doc = "`.\n\nIf a bit that doesn't correspond to an enum variant is set, this \
+                     method will return `None`."]
+            pub fn $try_from(bits: $underlying) -> Option<Self> {
+                let bits = T::Repr::$from_fn_opt(bits);
+                let mask = Self::all().__priv_repr;
+                bits.and_then(|bits| if bits.and_not(mask).is_empty() {
+                    Some(EnumSet { __priv_repr: bits })
+                } else {
+                    None
+                })
+            }
+
+            #[doc = "Constructs a bitset from a `"]
+            #[doc = $underlying_str]
+            #[doc = "`, ignoring invalid variants."]
+            pub fn $from_truncated(bits: $underlying) -> Self {
+                let mask = Self::all().$to_truncated();
+                let bits = <T::Repr as EnumSetTypeRepr>::$from_fn(bits & mask);
+                EnumSet { __priv_repr: bits }
+            }
+        )*}
+    }
+}
+conversion_impls! {
+    for_num!(u8, "u8", from_u8 to_u8 from_u8_opt to_u8_opt,
+             from_u8 try_from_u8 from_u8_truncated as_u8 try_as_u8 as_u8_truncated);
+    for_num!(u16, "u16", from_u16 to_u16 from_u16_opt to_u16_opt,
+             from_u16 try_from_u16 from_u16_truncated as_u16 try_as_u16 as_u16_truncated);
+    for_num!(u32, "u32", from_u32 to_u32 from_u32_opt to_u32_opt,
+             from_u32 try_from_u32 from_u32_truncated as_u32 try_as_u32 as_u32_truncated);
+    for_num!(u64, "u64", from_u64 to_u64 from_u64_opt to_u64_opt,
+             from_u64 try_from_u64 from_u64_truncated as_u64 try_as_u64 as_u64_truncated);
+    for_num!(u128, "u128", from_u128 to_u128 from_u128_opt to_u128_opt,
+             from_u128 try_from_u128 from_u128_truncated as_u128 try_as_u128 as_u128_truncated);
+    for_num!(usize, "usize", from_usize to_usize from_usize_opt to_usize_opt,
+             from_usize try_from_usize from_usize_truncated
+             as_usize try_as_usize as_usize_truncated);
+}
+
+impl <T: EnumSetType> Default for EnumSet<T> {
+    /// Returns an empty set.
+    fn default() -> Self {
+        Self::new()
     }
 }
-impl <T : EnumSetType> IntoIterator for EnumSet<T> {
+
+impl <T: EnumSetType> IntoIterator for EnumSet<T> {
     type Item = T;
     type IntoIter = EnumSetIter<T>;
 
@@ -347,73 +463,93 @@ impl <T : EnumSetType> IntoIterator for EnumSet<T> {
         self.iter()
     }
 }
+impl <T: EnumSetType> Sum for EnumSet<T> {
+    fn sum<I: Iterator<Item=Self>>(iter: I) -> Self {
+        iter.fold(EnumSet::empty(), |a, v| a | v)
+    }
+}
+impl <'a, T: EnumSetType> Sum<&'a EnumSet<T>> for EnumSet<T> {
+    fn sum<I: Iterator<Item=&'a Self>>(iter: I) -> Self {
+        iter.fold(EnumSet::empty(), |a, v| a | *v)
+    }
+}
+impl <T: EnumSetType> Sum<T> for EnumSet<T> {
+    fn sum<I: Iterator<Item=T>>(iter: I) -> Self {
+        iter.fold(EnumSet::empty(), |a, v| a | v)
+    }
+}
+impl <'a, T: EnumSetType> Sum<&'a T> for EnumSet<T> {
+    fn sum<I: Iterator<Item=&'a T>>(iter: I) -> Self {
+        iter.fold(EnumSet::empty(), |a, v| a | *v)
+    }
+}
 
-impl <T : EnumSetType, O: Into<EnumSet<T>>> Sub<O> for EnumSet<T> {
+impl <T: EnumSetType, O: Into<EnumSet<T>>> Sub<O> for EnumSet<T> {
     type Output = Self;
     fn sub(self, other: O) -> Self::Output {
         self.difference(other.into())
     }
 }
-impl <T : EnumSetType, O: Into<EnumSet<T>>> BitAnd<O> for EnumSet<T> {
+impl <T: EnumSetType, O: Into<EnumSet<T>>> BitAnd<O> for EnumSet<T> {
     type Output = Self;
     fn bitand(self, other: O) -> Self::Output {
         self.intersection(other.into())
     }
 }
-impl <T : EnumSetType, O: Into<EnumSet<T>>> BitOr<O> for EnumSet<T> {
+impl <T: EnumSetType, O: Into<EnumSet<T>>> BitOr<O> for EnumSet<T> {
     type Output = Self;
     fn bitor(self, other: O) -> Self::Output {
         self.union(other.into())
     }
 }
-impl <T : EnumSetType, O: Into<EnumSet<T>>> BitXor<O> for EnumSet<T> {
+impl <T: EnumSetType, O: Into<EnumSet<T>>> BitXor<O> for EnumSet<T> {
     type Output = Self;
     fn bitxor(self, other: O) -> Self::Output {
         self.symmetrical_difference(other.into())
     }
 }
 
-impl <T : EnumSetType, O: Into<EnumSet<T>>> SubAssign<O> for EnumSet<T> {
+impl <T: EnumSetType, O: Into<EnumSet<T>>> SubAssign<O> for EnumSet<T> {
     fn sub_assign(&mut self, rhs: O) {
         *self = *self - rhs;
     }
 }
-impl <T : EnumSetType, O: Into<EnumSet<T>>> BitAndAssign<O> for EnumSet<T> {
+impl <T: EnumSetType, O: Into<EnumSet<T>>> BitAndAssign<O> for EnumSet<T> {
     fn bitand_assign(&mut self, rhs: O) {
         *self = *self & rhs;
     }
 }
-impl <T : EnumSetType, O: Into<EnumSet<T>>> BitOrAssign<O> for EnumSet<T> {
+impl <T: EnumSetType, O: Into<EnumSet<T>>> BitOrAssign<O> for EnumSet<T> {
     fn bitor_assign(&mut self, rhs: O) {
         *self = *self | rhs;
     }
 }
-impl <T : EnumSetType, O: Into<EnumSet<T>>> BitXorAssign<O> for EnumSet<T> {
+impl <T: EnumSetType, O: Into<EnumSet<T>>> BitXorAssign<O> for EnumSet<T> {
     fn bitxor_assign(&mut self, rhs: O) {
         *self = *self ^ rhs;
     }
 }
 
-impl <T : EnumSetType> Not for EnumSet<T> {
+impl <T: EnumSetType> Not for EnumSet<T> {
     type Output = Self;
     fn not(self) -> Self::Output {
         self.complement()
     }
 }
 
-impl <T : EnumSetType> From<T> for EnumSet<T> {
+impl <T: EnumSetType> From<T> for EnumSet<T> {
     fn from(t: T) -> Self {
         EnumSet::only(t)
     }
 }
 
-impl <T : EnumSetType> PartialEq<T> for EnumSet<T> {
+impl <T: EnumSetType> PartialEq<T> for EnumSet<T> {
     fn eq(&self, other: &T) -> bool {
-        self.__enumset_underlying == EnumSet::<T>::mask(other.enum_into_u8())
+        self.__priv_repr == EnumSet::only(*other).__priv_repr
     }
 }
-impl <T : EnumSetType + Debug> Debug for EnumSet<T> {
-    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
+impl <T: EnumSetType + Debug> Debug for EnumSet<T> {
+    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
         let mut is_first = true;
         f.write_str("EnumSet(")?;
         for v in self.iter() {
@@ -426,51 +562,86 @@ impl <T : EnumSetType + Debug> Debug for EnumSet<T> {
     }
 }
 
-/// The iterator used by [`EnumSet`](./struct.EnumSet.html).
-#[derive(Copy, Clone, PartialOrd, Ord, PartialEq, Eq, Hash, Debug)]
-pub struct EnumSetIter<T : EnumSetType>(EnumSet<T>, u8);
-impl <T : EnumSetType> Iterator for EnumSetIter<T> {
+#[allow(clippy::derive_hash_xor_eq)] // This impl exists to change trait bounds only.
+impl <T: EnumSetType> Hash for EnumSet<T> {
+    fn hash<H: Hasher>(&self, state: &mut H) {
+        self.__priv_repr.hash(state)
+    }
+}
+impl <T: EnumSetType> PartialOrd for EnumSet<T> {
+    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
+        self.__priv_repr.partial_cmp(&other.__priv_repr)
+    }
+}
+impl <T: EnumSetType> Ord for EnumSet<T> {
+    fn cmp(&self, other: &Self) -> Ordering {
+        self.__priv_repr.cmp(&other.__priv_repr)
+    }
+}
+
+#[cfg(feature = "serde")]
+impl <T: EnumSetType> Serialize for EnumSet<T> {
+    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
+        T::serialize(*self, serializer)
+    }
+}
+
+#[cfg(feature = "serde")]
+impl <'de, T: EnumSetType> Deserialize<'de> for EnumSet<T> {
+    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
+        T::deserialize(deserializer)
+    }
+}
+
+/// The iterator used by [`EnumSet`]s.
+#[derive(Clone, Debug)]
+pub struct EnumSetIter<T: EnumSetType>(EnumSet<T>);
+impl <T: EnumSetType> Iterator for EnumSetIter<T> {
     type Item = T;
 
     fn next(&mut self) -> Option<Self::Item> {
-        while self.1 < EnumSet::<T>::bit_width() {
-            let bit = self.1;
-            self.1 += 1;
-            if self.0.has_bit(bit) {
-                return unsafe { Some(T::enum_from_u8(bit)) }
-            }
+        if self.0.is_empty() {
+            None
+        } else {
+            let bit = self.0.__priv_repr.trailing_zeros();
+            self.0.__priv_repr.remove_bit(bit);
+            unsafe { Some(T::enum_from_u32(bit)) }
         }
-        None
     }
     fn size_hint(&self) -> (usize, Option<usize>) {
-        let left_mask = EnumSet::<T>::partial_bits(self.1);
-        let left = (self.0.__enumset_underlying & left_mask).count_ones() as usize;
+        let left = self.0.len();
         (left, Some(left))
     }
 }
 
-/// Defines enums which can be used with EnumSet.
-///
-/// [`Copy`], [`Clone`], [`PartialOrd`], [`Ord`], [`PartialEq`], [`Eq`], [`Hash`], [`Debug`],
-/// [`Sub`], [`BitAnd`], [`BitOr`], [`BitXor`], and [`Not`] are automatically derived for the enum.
-///
-/// These impls, in general, behave as if the enum variant was an [`EnumSet`] with a single value,
-/// as those created by [`EnumSet::only`].
-#[macro_export]
-#[deprecated(since = "0.3.13", note = "Use `#[derive(EnumSetType)] instead.")]
-macro_rules! enum_set_type {
-    ($(#[$enum_attr:meta])* $vis:vis enum $enum_name:ident {
-        $($(#[$attr:meta])* $variant:ident),* $(,)*
-    } $($rest:tt)*) => {
-        $(#[$enum_attr])* #[repr(u8)]
-        #[derive($crate::EnumSetType, Debug)]
-        $vis enum $enum_name {
-            $($(#[$attr])* $variant,)*
-        }
+impl<T: EnumSetType> ExactSizeIterator for EnumSetIter<T> {}
 
-        enum_set_type!($($rest)*);
-    };
-    () => { };
+impl<T: EnumSetType> Extend<T> for EnumSet<T> {
+    fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I) {
+        iter.into_iter().for_each(|v| { self.insert(v); });
+    }
+}
+
+impl<T: EnumSetType> FromIterator<T> for EnumSet<T> {
+    fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self {
+        let mut set = EnumSet::default();
+        set.extend(iter);
+        set
+    }
+}
+
+impl<T: EnumSetType> Extend<EnumSet<T>> for EnumSet<T> {
+    fn extend<I: IntoIterator<Item = EnumSet<T>>>(&mut self, iter: I) {
+        iter.into_iter().for_each(|v| { self.insert_all(v); });
+    }
+}
+
+impl<T: EnumSetType> FromIterator<EnumSet<T>> for EnumSet<T> {
+    fn from_iter<I: IntoIterator<Item = EnumSet<T>>>(iter: I) -> Self {
+        let mut set = EnumSet::default();
+        set.extend(iter);
+        set
+    }
 }
 
 /// Creates a EnumSet literal, which can be used in const contexts.
@@ -478,8 +649,7 @@ macro_rules! enum_set_type {
 /// The syntax used is `enum_set!(Type::A | Type::B | Type::C)`. Each variant must be of the same
 /// type, or a error will occur at compile-time.
 ///
-/// You may also explicitly state the type of the variants that follow, as in
-/// `enum_set!(Type, Type::A | Type::B | Type::C)`.
+/// This macro accepts trailing `|`s to allow easier use in other macros.
 ///
 /// # Examples
 ///
@@ -488,9 +658,6 @@ macro_rules! enum_set_type {
 /// # #[derive(EnumSetType, Debug)] enum Enum { A, B, C }
 /// const CONST_SET: EnumSet<Enum> = enum_set!(Enum::A | Enum::B);
 /// assert_eq!(CONST_SET, Enum::A | Enum::B);
-///
-/// const EXPLICIT_CONST_SET: EnumSet<Enum> = enum_set!(Enum, Enum::A | Enum::B);
-/// assert_eq!(EXPLICIT_CONST_SET, Enum::A | Enum::B);
 /// ```
 ///
 /// This macro is strongly typed. For example, the following will not compile:
@@ -503,220 +670,20 @@ macro_rules! enum_set_type {
 /// ```
 #[macro_export]
 macro_rules! enum_set {
-    () => {
-        $crate::EnumSet { __enumset_underlying: 0 }
+    ($(|)*) => {
+        $crate::EnumSet { __priv_repr: 0 }
     };
-    ($($value:path)|* $(|)*) => {
-        $crate::internal::EnumSetSameTypeHack {
-            unified: &[$($value,)*],
-            enum_set: $crate::EnumSet {
-                __enumset_underlying: 0 $(| (1 << ($value as u8)))*
-            },
-        }.enum_set
-    };
-    ($enum_name:ty, $($value:path)|* $(|)*) => {
-        $crate::EnumSet::<$enum_name> {
-            __enumset_underlying: 0 $(| (1 << ($value as $enum_name as u8)))*
-        }
-    }
-}
-
-#[cfg(test)]
-#[allow(dead_code)]
-mod test {
-    use super::*;
-
-    mod enums {
-        #[derive(::EnumSetType, Debug)]
-        pub enum SmallEnum {
-            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,
-        }
-        #[derive(::EnumSetType, Debug)]
-        pub enum LargeEnum {
-            _00,  _01,  _02,  _03,  _04,  _05,  _06,  _07,
-            _10,  _11,  _12,  _13,  _14,  _15,  _16,  _17,
-            _20,  _21,  _22,  _23,  _24,  _25,  _26,  _27,
-            _30,  _31,  _32,  _33,  _34,  _35,  _36,  _37,
-            _40,  _41,  _42,  _43,  _44,  _45,  _46,  _47,
-            _50,  _51,  _52,  _53,  _54,  _55,  _56,  _57,
-            _60,  _61,  _62,  _63,  _64,  _65,  _66,  _67,
-            _70,  _71,  _72,  _73,  _74,  _75,  _76,  _77,
-            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,
-        }
-        #[derive(::EnumSetType, Debug)]
-        pub enum Enum8 {
-            A, B, C, D, E, F, G, H,
-        }
-        #[derive(::EnumSetType, Debug)]
-        pub enum Enum128 {
-            A, B, C, D, E, F, G, H, _8, _9, _10, _11, _12, _13, _14, _15,
-            _16, _17, _18, _19, _20, _21, _22, _23, _24, _25, _26, _27, _28, _29, _30, _31,
-            _32, _33, _34, _35, _36, _37, _38, _39, _40, _41, _42, _43, _44, _45, _46, _47,
-            _48, _49, _50, _51, _52, _53, _54, _55, _56, _57, _58, _59, _60, _61, _62, _63,
-            _64, _65, _66, _67, _68, _69, _70, _71, _72, _73, _74, _75, _76, _77, _78, _79,
-            _80, _81, _82, _83, _84, _85, _86, _87, _88, _89, _90, _91, _92, _93, _94, _95,
-            _96, _97, _98, _99, _100, _101, _102, _103, _104, _105, _106, _107, _108, _109,
-            _110, _111, _112, _113, _114, _115, _116, _117, _118, _119, _120, _121, _122,
-            _123, _124,  _125, _126, _127,
-        }
-        #[derive(::EnumSetType, Debug)]
-        pub enum SparseEnum {
-            A = 10, B = 20, C = 30, D = 40, E = 50, F = 60, G = 70, H = 80,
-        }
-    }
-    use self::enums::*;
-
-    macro_rules! test_variants {
-        ($enum_name:ident $all_empty_test:ident $($variant:ident,)*) => {
-            #[test]
-            fn $all_empty_test() {
-                let all = EnumSet::<$enum_name>::all();
-                let empty = EnumSet::<$enum_name>::empty();
-
-                $(
-                    assert!(!empty.contains($enum_name::$variant));
-                    assert!(all.contains($enum_name::$variant));
-                )*
-            }
+    ($value:path $(|)*) => {
+        {
+            #[allow(deprecated)] let value = $value.__impl_enumset_internal__const_only();
+            value
         }
-    }
-    test_variants! { SmallEnum small_enum_all_empty
-        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,
-    }
-    test_variants! { LargeEnum large_enum_all_empty
-        _00,  _01,  _02,  _03,  _04,  _05,  _06,  _07,
-        _10,  _11,  _12,  _13,  _14,  _15,  _16,  _17,
-        _20,  _21,  _22,  _23,  _24,  _25,  _26,  _27,
-        _30,  _31,  _32,  _33,  _34,  _35,  _36,  _37,
-        _40,  _41,  _42,  _43,  _44,  _45,  _46,  _47,
-        _50,  _51,  _52,  _53,  _54,  _55,  _56,  _57,
-        _60,  _61,  _62,  _63,  _64,  _65,  _66,  _67,
-        _70,  _71,  _72,  _73,  _74,  _75,  _76,  _77,
-        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,
-    }
-    test_variants! { SparseEnum sparse_enum_all_empty
-        A, B, C, D, E, F, G,
-    }
-
-    macro_rules! test_enum {
-        ($e:ident, $m:ident) => {
-            mod $m {
-                use super::*;
-
-                const CONST_SET: EnumSet<$e> = enum_set!($e, $e::A | $e::C);
-                const EMPTY_SET: EnumSet<$e> = enum_set!();
-                #[test]
-                fn const_set() {
-                    assert_eq!(CONST_SET.len(), 2);
-                    assert!(CONST_SET.contains($e::A));
-                    assert!(CONST_SET.contains($e::C));
-                    assert!(EMPTY_SET.is_empty());
-                }
-
-                #[test]
-                fn basic_add_remove() {
-                    let mut set = EnumSet::new();
-                    set.insert($e::A);
-                    set.insert($e::B);
-                    set.insert($e::C);
-                    assert_eq!(set, $e::A | $e::B | $e::C);
-                    set.remove($e::B);
-                    assert_eq!(set, $e::A | $e::C);
-                    set.insert($e::D);
-                    assert_eq!(set, $e::A | $e::C | $e::D);
-                    set.insert_all($e::F | $e::E | $e::G);
-                    assert_eq!(set, $e::A | $e::C | $e::D | $e::F | $e::E | $e::G);
-                    set.remove_all($e::A | $e::D | $e::G);
-                    assert_eq!(set, $e::C | $e::F | $e::E);
-                    assert!(!set.is_empty());
-                    set.clear();
-                    assert!(set.is_empty());
-                }
-
-                #[test]
-                fn empty_is_empty() {
-                    assert_eq!(EnumSet::<$e>::empty().len(), 0)
-                }
-
-                #[test]
-                fn all_len() {
-                    assert_eq!(EnumSet::<$e>::all().len(), EnumSet::<$e>::variant_count() as usize)
-                }
-
-                #[test]
-                fn basic_iter_test() {
-                    let mut set = EnumSet::new();
-                    set.insert($e::A);
-                    set.insert($e::B);
-                    set.insert($e::C);
-                    set.insert($e::E);
-
-                    let mut set_2 = EnumSet::new();
-                    let vec: Vec<$e> = set.iter().collect();
-                    for val in vec {
-                        assert!(!set_2.contains(val));
-                        set_2.insert(val);
-                    }
-                    assert_eq!(set, set_2);
-
-                    let mut set_3 = EnumSet::new();
-                    for val in set {
-                        assert!(!set_3.contains(val));
-                        set_3.insert(val);
-                    }
-                    assert_eq!(set, set_3);
-                }
-
-                #[test]
-                fn basic_ops_test() {
-                    assert_eq!(($e::A | $e::B) | ($e::B | $e::C), $e::A | $e::B | $e::C);
-                    assert_eq!(($e::A | $e::B) & ($e::B | $e::C), $e::B);
-                    assert_eq!(($e::A | $e::B) ^ ($e::B | $e::C), $e::A | $e::C);
-                    assert_eq!(($e::A | $e::B) - ($e::B | $e::C), $e::A);
-                }
-
-                #[test]
-                fn basic_set_status() {
-                    assert!(($e::A | $e::B | $e::C).is_disjoint($e::D | $e::E | $e::F));
-                    assert!(!($e::A | $e::B | $e::C | $e::D).is_disjoint($e::D | $e::E | $e::F));
-                    assert!(($e::A | $e::B).is_subset($e::A | $e::B | $e::C));
-                    assert!(!($e::A | $e::D).is_subset($e::A | $e::B | $e::C));
-                }
-
-                #[test]
-                fn debug_impl() {
-                    assert_eq!(format!("{:?}", $e::A | $e::B | $e::D), "EnumSet(A | B | D)");
-                }
-
-                #[test]
-                fn to_from_bits() {
-                    let value = $e::A | $e::C | $e::D | $e::F | $e::E | $e::G;
-                    assert_eq!(EnumSet::from_bits(value.to_bits()), value);
-                }
-
-                #[test]
-                #[should_panic]
-                fn too_many_bits() {
-                    if EnumSet::<$e>::variant_count() == 128 {
-                        panic!("(test skipped)")
-                    }
-                    EnumSet::<$e>::from_bits(!0);
-                }
-
-                #[test]
-                fn match_const_test() {
-                    match CONST_SET {
-                        CONST_SET => { /* ok */ }
-                        _ => panic!("match fell through?"),
-                    }
-                }
-            }
+    };
+    ($value:path | $($rest:path)|* $(|)*) => {
+        {
+            #[allow(deprecated)] let value = $value.__impl_enumset_internal__const_only();
+            $(#[allow(deprecated)] let value = $rest.__impl_enumset_internal__const_merge(value);)*
+            value
         }
-    }
-
-    test_enum!(SmallEnum, small_enum);
-    test_enum!(LargeEnum, large_enum);
-    test_enum!(Enum8, enum8);
-    test_enum!(Enum128, enum128);
-    test_enum!(SparseEnum, sparse_enum);
+    };
 }