X-Git-Url: https://git.lizzy.rs/?a=blobdiff_plain;f=enumset%2Fsrc%2Flib.rs;h=bde7910bebe0673cfa1ad8de9d8df9e070b602f6;hb=34aadb450256fde6e896cb8e74a373aa4ce430cd;hp=04b76f75bab871d5b13e61c2fa7b6771cd4835b0;hpb=4b2cdaea448f2e01806eaa1ce6e9af9fb2df3a00;p=enumset.git diff --git a/enumset/src/lib.rs b/enumset/src/lib.rs index 04b76f7..bde7910 100644 --- a/enumset/src/lib.rs +++ b/enumset/src/lib.rs @@ -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)]`: @@ -30,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 @@ -71,17 +73,13 @@ //! assert_eq!(set, Enum::A | Enum::E | Enum::G); //! ``` -#[cfg(test)] extern crate core; -extern crate enumset_derive; -extern crate num_traits; -#[cfg(feature = "serde")] extern crate serde; - pub use enumset_derive::*; -mod enumset { pub use super::*; } +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; use core::ops::*; use num_traits::*; @@ -91,7 +89,6 @@ use num_traits::*; 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], @@ -99,18 +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(set: EnumSet, ser: S) -> Result + where Self: EnumSetType; + #[cfg(feature = "serde")] + fn deserialize<'de, D: serde::Deserializer<'de>>(de: D) -> Result, 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 + AsPrimitive + AsPrimitive + AsPrimitive + + AsPrimitive + AsPrimitive + { + 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`]. /// @@ -129,14 +165,13 @@ use private::EnumSetTypeRepr; /// /// # Custom Derive /// -/// The custom derive for `EnumSetType` automatically creates implementations of [`PartialEq`], +/// 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. @@ -147,7 +182,7 @@ use private::EnumSetTypeRepr; /// /// ```rust /// # use enumset::*; -/// #[derive(EnumSetType, Debug)] +/// #[derive(EnumSetType)] /// pub enum Enum { /// A, B, C, D, E, F, G, /// } @@ -157,7 +192,7 @@ use private::EnumSetTypeRepr; /// /// ```rust /// # use enumset::*; -/// #[derive(EnumSetType, Debug)] +/// #[derive(EnumSetType)] /// pub enum SparseEnum { /// A = 10, B = 20, C = 30, D = 127, /// } @@ -167,37 +202,51 @@ 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 { +/// +/// It is implemented using a bitset stored using the smallest integer that can fit all bits +/// in the underlying enum. +/// +/// # Serialization +/// +/// 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 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 of enum variants. This requires your enum type implement +/// [`Serialize`] and [`Deserialize`]. +#[derive(Copy, Clone, PartialEq, Eq)] +pub struct EnumSet { #[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 EnumSet { - fn mask(bit: u8) -> T::Repr { +impl EnumSet { + fn mask(bit: u32) -> T::Repr { Shl::::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()) } @@ -207,65 +256,50 @@ impl EnumSet { 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() } @@ -274,55 +308,63 @@ impl EnumSet { 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 } @@ -336,11 +378,111 @@ impl EnumSet { } /// 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 { EnumSetIter(*self, 0) } } -impl IntoIterator for EnumSet { + +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 EnumSet {$( + #[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 { + let bits = ::$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 = ::$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 Default for EnumSet { + /// Returns an empty set. + fn default() -> Self { + Self::new() + } +} + +impl IntoIterator for EnumSet { type Item = T; type IntoIter = EnumSetIter; @@ -349,72 +491,72 @@ impl IntoIterator for EnumSet { } } -impl >> Sub for EnumSet { +impl >> Sub for EnumSet { type Output = Self; fn sub(self, other: O) -> Self::Output { self.difference(other.into()) } } -impl >> BitAnd for EnumSet { +impl >> BitAnd for EnumSet { type Output = Self; fn bitand(self, other: O) -> Self::Output { self.intersection(other.into()) } } -impl >> BitOr for EnumSet { +impl >> BitOr for EnumSet { type Output = Self; fn bitor(self, other: O) -> Self::Output { self.union(other.into()) } } -impl >> BitXor for EnumSet { +impl >> BitXor for EnumSet { type Output = Self; fn bitxor(self, other: O) -> Self::Output { self.symmetrical_difference(other.into()) } } -impl >> SubAssign for EnumSet { +impl >> SubAssign for EnumSet { fn sub_assign(&mut self, rhs: O) { *self = *self - rhs; } } -impl >> BitAndAssign for EnumSet { +impl >> BitAndAssign for EnumSet { fn bitand_assign(&mut self, rhs: O) { *self = *self & rhs; } } -impl >> BitOrAssign for EnumSet { +impl >> BitOrAssign for EnumSet { fn bitor_assign(&mut self, rhs: O) { *self = *self | rhs; } } -impl >> BitXorAssign for EnumSet { +impl >> BitXorAssign for EnumSet { fn bitxor_assign(&mut self, rhs: O) { *self = *self ^ rhs; } } -impl Not for EnumSet { +impl Not for EnumSet { type Output = Self; fn not(self) -> Self::Output { self.complement() } } -impl From for EnumSet { +impl From for EnumSet { fn from(t: T) -> Self { EnumSet::only(t) } } -impl PartialEq for EnumSet { +impl PartialEq for EnumSet { fn eq(&self, other: &T) -> bool { - self.__enumset_underlying == EnumSet::::mask(other.enum_into_u8()) + self.__enumset_underlying == EnumSet::::mask(other.enum_into_u32()) } } -impl Debug for EnumSet { - fn fmt(&self, f: &mut Formatter) -> fmt::Result { +impl Debug for EnumSet { + fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { let mut is_first = true; f.write_str("EnumSet(")?; for v in self.iter() { @@ -427,30 +569,40 @@ impl Debug for EnumSet { } } +impl Hash for EnumSet { + fn hash(&self, state: &mut H) { + self.__enumset_underlying.hash(state) + } +} +impl PartialOrd for EnumSet { + fn partial_cmp(&self, other: &Self) -> Option { + self.__enumset_underlying.partial_cmp(&other.__enumset_underlying) + } +} +impl Ord for EnumSet { + fn cmp(&self, other: &Self) -> Ordering { + self.__enumset_underlying.cmp(&other.__enumset_underlying) + } +} + #[cfg(feature = "serde")] -impl serde::Serialize for EnumSet { - fn serialize(&self, serializer: S) -> Result - where - S: serde::Serializer, - { - serializer.serialize_u128(self.to_bits()) +impl Serialize for EnumSet { + fn serialize(&self, serializer: S) -> Result { + T::serialize(*self, serializer) } } #[cfg(feature = "serde")] -impl <'de, T : EnumSetType > serde::Deserialize<'de> for EnumSet { - fn deserialize(deserializer: D) -> Result - where - D: serde::Deserializer<'de>, - { - u128::deserialize(deserializer).map(EnumSet::from_bits) +impl <'de, T: EnumSetType> Deserialize<'de> for EnumSet { + fn deserialize>(deserializer: D) -> Result { + T::deserialize(deserializer) } } -/// The iterator used by [`EnumSet`](./struct.EnumSet.html). -#[derive(Copy, Clone, PartialOrd, Ord, PartialEq, Eq, Hash, Debug)] -pub struct EnumSetIter(EnumSet, u8); -impl Iterator for EnumSetIter { +/// The iterator used by [`EnumSet`]s. +#[derive(Clone, Debug)] +pub struct EnumSetIter(EnumSet, u32); +impl Iterator for EnumSetIter { type Item = T; fn next(&mut self) -> Option { @@ -458,40 +610,44 @@ impl Iterator for EnumSetIter { 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) { - let left_mask = EnumSet::::partial_bits(self.1); + let left_mask = !EnumSet::::partial_bits(self.1); let left = (self.0.__enumset_underlying & left_mask).count_ones() as usize; (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 Extend for EnumSet { + fn extend>(&mut self, iter: I) { + iter.into_iter().for_each(|v| { self.insert(v); }); + } +} - enum_set_type!($($rest)*); - }; - () => { }; +impl FromIterator for EnumSet { + fn from_iter>(iter: I) -> Self { + let mut set = EnumSet::default(); + set.extend(iter); + set + } +} + +impl Extend> for EnumSet { + fn extend>>(&mut self, iter: I) { + iter.into_iter().for_each(|v| { self.insert_all(v); }); + } +} + +impl FromIterator> for EnumSet { + fn from_iter>>(iter: I) -> Self { + let mut set = EnumSet::default(); + set.extend(iter); + set + } } /// Creates a EnumSet literal, which can be used in const contexts. @@ -499,9 +655,6 @@ 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)`. -/// /// # Examples /// /// ```rust @@ -509,9 +662,6 @@ macro_rules! enum_set_type { /// # #[derive(EnumSetType, Debug)] enum Enum { A, B, C } /// const CONST_SET: EnumSet = enum_set!(Enum::A | Enum::B); /// assert_eq!(CONST_SET, Enum::A | Enum::B); -/// -/// const EXPLICIT_CONST_SET: EnumSet = 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: @@ -531,213 +681,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)))* - } - } -} - -#[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)); - )* - } - } - } - 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?"), - } - } - } - } - } - - test_enum!(SmallEnum, small_enum); - test_enum!(LargeEnum, large_enum); - test_enum!(Enum8, enum8); - test_enum!(Enum128, enum128); - test_enum!(SparseEnum, sparse_enum); }