]> git.lizzy.rs Git - enumset.git/blobdiff - enumset/src/lib.rs
Rename from_u128/to_u128 series slightly.
[enumset.git] / enumset / src / lib.rs
index 59d9fa7764543db4fd4f0598bdb4444a186812b2..580debab9f1d4f0d0e43c5482a8bda27ead889c6 100644 (file)
@@ -32,7 +32,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
@@ -79,8 +79,8 @@ use core::cmp::Ordering;
 use core::fmt;
 use core::fmt::{Debug, Formatter};
 use core::hash::{Hash, Hasher};
+use core::iter::FromIterator;
 use core::ops::*;
-use serde2 as serde;
 
 use num_traits::*;
 
@@ -96,21 +96,57 @@ pub mod internal {
     }
 
     /// A reexport of core to allow our macros to be generic to std vs core.
-    pub extern crate core;
+    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 {
+        type Repr: EnumSetTypeRepr;
+        const ALL_BITS: Self::Repr;
+        fn enum_into_u32(self) -> u32;
+        unsafe fn enum_from_u32(val: u32) -> Self;
+
+        #[cfg(feature = "serde")]
+        fn serialize<S: serde::Serializer>(set: EnumSet<Self>, ser: S) -> Result<S::Ok, S::Error>
+            where Self: EnumSetType;
+        #[cfg(feature = "serde")]
+        fn deserialize<'de, D: serde::Deserializer<'de>>(de: D) -> Result<EnumSet<Self>, D::Error>
+            where Self: EnumSetType;
+    }
 }
+use crate::internal::EnumSetTypePrivate;
+#[cfg(feature = "serde")] use crate::internal::serde;
+#[cfg(feature = "serde")] use crate::serde::{Serialize, Deserialize};
 
 mod private {
     use super::*;
-    pub trait EnumSetTypeRepr : PrimInt + FromPrimitive + WrappingSub + CheckedShl + Debug + Hash {
-        const WIDTH: u8;
+
+    pub trait EnumSetTypeRepr :
+        PrimInt + WrappingSub + CheckedShl + Debug + Hash + FromPrimitive + ToPrimitive +
+        AsPrimitive<u8> + AsPrimitive<u16> + AsPrimitive<u32> + AsPrimitive<u64> +
+        AsPrimitive<u128> + AsPrimitive<usize>
+    {
+        const WIDTH: u32;
+
+        fn from_u8(v: u8) -> Self;
+        fn from_u16(v: u16) -> Self;
+        fn from_u32(v: u32) -> Self;
+        fn from_u64(v: u64) -> Self;
+        fn from_u128(v: u128) -> Self;
+        fn from_usize(v: usize) -> Self;
     }
     macro_rules! prim {
         ($name:ty, $width:expr) => {
             impl EnumSetTypeRepr for $name {
-                const WIDTH: u8 = $width;
+                const WIDTH: u32 = $width;
+                fn from_u8(v: u8) -> Self { v.as_() }
+                fn from_u16(v: u16) -> Self { v.as_() }
+                fn from_u32(v: u32) -> Self { v.as_() }
+                fn from_u64(v: u64) -> Self { v.as_() }
+                fn from_u128(v: u128) -> Self { v.as_() }
+                fn from_usize(v: usize) -> Self { v.as_() }
             }
         }
     }
@@ -120,7 +156,7 @@ mod private {
     prim!(u64 , 64 );
     prim!(u128, 128);
 }
-use private::EnumSetTypeRepr;
+use crate::private::EnumSetTypeRepr;
 
 /// The trait used to define enum types that may be used with [`EnumSet`].
 ///
@@ -172,52 +208,45 @@ use private::EnumSetTypeRepr;
 ///    A, B, C, D, E, F, G,
 /// }
 /// ```
-pub unsafe trait EnumSetType: Copy + Eq {
-    #[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;
-
-    #[cfg(feature = "serde")] #[doc(hidden)]
-    fn serialize<S: serde::Serializer>(set: EnumSet<Self>, ser: S) -> Result<S::Ok, S::Error>;
-    #[cfg(feature = "serde")] #[doc(hidden)]
-    fn deserialize<'de, D: serde::Deserializer<'de>>(de: D) -> Result<EnumSet<Self>, D::Error>;
-}
+pub unsafe trait EnumSetType: Copy + Eq + EnumSetTypePrivate { }
 
 /// An efficient set type for enums.
 ///
+/// It is implemented using a bitset stored using the smallest integer that can fit all bits
+/// in the underlying enum.
+///
 /// # Serialization
 ///
-/// The default representation serializes enumsets as an `u8`, `u16`, `u32`, `u64`, or `u128`,
-/// whichever is the smallest that can contain all bits that are part of the set.
+/// By default, `EnumSet`s are serialized as an unsigned integer of the same width as used to store
+/// it in memory.
 ///
 /// Unknown bits are ignored, and are simply dropped. To override this behavior, you can add a
 /// `#[enumset(serialize_deny_unknown)]` annotation to your enum.
 ///
-/// You can add a `#[enumset(serialize_repr = "u8")]` annotation to your enum to explicitly set
-/// the bit width the `EnumSet` is serialized as. This can be used to avoid breaking changes in
-/// certain serialization formats (such as `bincode`).
+/// You can add a `#[enumset(serialize_repr = "u8")]` annotation to your enum to manually set
+/// the number width the `EnumSet` is serialized as. Only unsigned integer types may be used. This
+/// can be used to avoid breaking changes in certain serialization formats (such as `bincode`).
 ///
 /// In addition, the `#[enumset(serialize_as_list)]` annotation causes the `EnumSet` to be
-/// instead serialized as a list. This requires your enum type implement [`Serialize`] and
-/// [`Deserialize`].
+/// instead serialized as a list of enum variants. This requires your enum type implement
+/// [`Serialize`] and [`Deserialize`].
 #[derive(Copy, Clone, PartialEq, Eq)]
-pub struct EnumSet<T : EnumSetType> {
+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
 }
-impl <T : EnumSetType> EnumSet<T> {
-    fn mask(bit: u8) -> T::Repr {
+impl <T: EnumSetType> EnumSet<T> {
+    fn mask(bit: u32) -> T::Repr {
         Shl::<usize>::shl(T::Repr::one(), bit as usize)
     }
-    fn has_bit(&self, bit: u8) -> bool {
+    fn has_bit(&self, bit: u32) -> 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())
+    fn partial_bits(bits: u32) -> T::Repr {
+        T::Repr::one().checked_shl(bits as u32)
             .unwrap_or(T::Repr::zero())
             .wrapping_sub(&T::Repr::one())
     }
@@ -227,65 +256,50 @@ impl <T : EnumSetType> EnumSet<T> {
         T::ALL_BITS
     }
 
-    /// Returns an empty set.
+    /// Creates an empty `EnumSet`.
     pub fn new() -> Self {
         EnumSet { __enumset_underlying: T::Repr::zero() }
     }
 
-    /// 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()) }
+        EnumSet { __enumset_underlying: Self::mask(t.enum_into_u32()) }
     }
 
-    /// 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() }
     }
 
-    /// 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
+    pub fn variant_count() -> u32 {
+        T::ALL_BITS.count_ones()
     }
 
-    /// 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?")
-        }
-    }
-
-    /// 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
     }
-    /// 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()
     }
@@ -294,55 +308,63 @@ impl <T : EnumSetType> EnumSet<T> {
         self.__enumset_underlying = T::Repr::zero()
     }
 
-    /// 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
     }
-    /// 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 }
     }
-    /// 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 }
     }
-    /// 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 }
     }
-    /// 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 }
     }
-    /// 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() }
     }
 
     /// Checks whether this set contains a value.
     pub fn contains(&self, value: T) -> bool {
-        self.has_bit(value.enum_into_u8())
+        self.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.__enumset_underlying = self.__enumset_underlying | Self::mask(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.__enumset_underlying = self.__enumset_underlying & !Self::mask(value.enum_into_u32());
         contains
     }
 
@@ -356,11 +378,103 @@ impl <T : EnumSetType> EnumSet<T> {
     }
 
     /// 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)
     }
 }
 
+macro_rules! conversion_impls {
+    (
+        $(for_num!(
+            $underlying:ty, $underlying_str:expr, $from_fn:ident, $to_fn: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> {
+                self.__enumset_underlying.$to_fn()
+            }
+
+            #[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 {
+                AsPrimitive::<$underlying>::as_(self.__enumset_underlying)
+            }
+
+            #[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 as FromPrimitive>::$from_fn(bits);
+                let mask = Self::all().__enumset_underlying;
+                bits.and_then(|bits| if (bits & !mask) == T::Repr::zero() {
+                    Some(EnumSet { __enumset_underlying: 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 { __enumset_underlying: bits }
+            }
+        )*}
+    }
+}
+
+conversion_impls! {
+    for_num!(u8, "u8", from_u8, to_u8,
+             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 try_from_u16 from_u16_truncated as_u16 try_as_u16 as_u16_truncated);
+    for_num!(u32, "u32", from_u32, to_u32,
+             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 try_from_u64 from_u64_truncated as_u64 try_as_u64 as_u64_truncated);
+    for_num!(u128, "u128", from_u128, to_u128,
+             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 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 {
@@ -368,7 +482,7 @@ impl <T: EnumSetType> Default for EnumSet<T> {
     }
 }
 
-impl <T : EnumSetType> IntoIterator for EnumSet<T> {
+impl <T: EnumSetType> IntoIterator for EnumSet<T> {
     type Item = T;
     type IntoIter = EnumSetIter<T>;
 
@@ -377,71 +491,71 @@ impl <T : EnumSetType> IntoIterator for EnumSet<T> {
     }
 }
 
-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.__enumset_underlying == EnumSet::<T>::mask(other.enum_into_u32())
     }
 }
-impl <T : EnumSetType + Debug> Debug for EnumSet<T> {
+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(")?;
@@ -472,23 +586,23 @@ impl <T: EnumSetType> Ord for EnumSet<T> {
 }
 
 #[cfg(feature = "serde")]
-impl <T : EnumSetType> serde::Serialize for EnumSet<T> {
+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> serde::Deserialize<'de> for EnumSet<T> {
+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`](./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> {
+/// The iterator used by [`EnumSet`]s.
+#[derive(Clone, Debug)]
+pub struct EnumSetIter<T: EnumSetType>(EnumSet<T>, u32);
+impl <T: EnumSetType> Iterator for EnumSetIter<T> {
     type Item = T;
 
     fn next(&mut self) -> Option<Self::Item> {
@@ -496,26 +610,37 @@ impl <T : EnumSetType> Iterator for EnumSetIter<T> {
             let bit = self.1;
             self.1 += 1;
             if self.0.has_bit(bit) {
-                return unsafe { Some(T::enum_from_u8(bit)) }
+                return 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_mask = !EnumSet::<T>::partial_bits(self.1);
         let left = (self.0.__enumset_underlying & left_mask).count_ones() as usize;
         (left, Some(left))
     }
 }
 
+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
+    }
+}
+
 /// Creates a EnumSet literal, which can be used in const contexts.
 ///
 /// 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)`.
-///
 /// # Examples
 ///
 /// ```rust
@@ -523,9 +648,6 @@ impl <T : EnumSetType> Iterator for EnumSetIter<T> {
 /// # #[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:
@@ -545,13 +667,8 @@ macro_rules! enum_set {
         $crate::internal::EnumSetSameTypeHack {
             unified: &[$($value,)*],
             enum_set: $crate::EnumSet {
-                __enumset_underlying: 0 $(| (1 << ($value as u8)))*
+                __enumset_underlying: 0 $(| (1 << ($value as u32)))*
             },
         }.enum_set
     };
-    ($enum_name:ty, $($value:path)|* $(|)*) => {
-        $crate::EnumSet::<$enum_name> {
-            __enumset_underlying: 0 $(| (1 << ($value as $enum_name as u8)))*
-        }
-    }
 }