2 #![forbid(missing_docs)]
4 // The safety requirement is "use the procedural derive".
5 #![allow(clippy::missing_safety_doc)]
7 //! A library for defining enums that can be used in compact bit sets. It supports enums up to 128
8 //! variants, and has a macro to use these sets in constants.
10 //! For serde support, enable the `serde` feature.
12 //! # Defining enums for use with EnumSet
14 //! Enums to be used with [`EnumSet`] should be defined using `#[derive(EnumSetType)]`:
18 //! #[derive(EnumSetType, Debug)]
20 //! A, B, C, D, E, F, G,
24 //! For more information on more advanced use cases, see the documentation for
25 //! [`#[derive(EnumSetType)]`](./derive.EnumSetType.html).
27 //! # Working with EnumSets
29 //! EnumSets can be constructed via [`EnumSet::new()`] like a normal set. In addition,
30 //! `#[derive(EnumSetType)]` creates operator overloads that allow you to create EnumSets like so:
34 //! # #[derive(EnumSetType, Debug)] pub enum Enum { A, B, C, D, E, F, G }
35 //! let new_set = Enum::A | Enum::C | Enum::G;
36 //! assert_eq!(new_set.len(), 3);
39 //! All bitwise operations you would expect to work on bitsets also work on both EnumSets and
40 //! enums with `#[derive(EnumSetType)]`:
43 //! # #[derive(EnumSetType, Debug)] pub enum Enum { A, B, C, D, E, F, G }
44 //! // Intersection of sets
45 //! assert_eq!((Enum::A | Enum::B) & Enum::C, EnumSet::empty());
46 //! assert_eq!((Enum::A | Enum::B) & Enum::A, Enum::A);
47 //! assert_eq!(Enum::A & Enum::B, EnumSet::empty());
49 //! // Symmetric difference of sets
50 //! assert_eq!((Enum::A | Enum::B) ^ (Enum::B | Enum::C), Enum::A | Enum::C);
51 //! assert_eq!(Enum::A ^ Enum::C, Enum::A | Enum::C);
53 //! // Difference of sets
54 //! assert_eq!((Enum::A | Enum::B | Enum::C) - Enum::B, Enum::A | Enum::C);
56 //! // Complement of sets
57 //! assert_eq!(!(Enum::E | Enum::G), Enum::A | Enum::B | Enum::C | Enum::D | Enum::F);
60 //! The [`enum_set!`] macro allows you to create EnumSets in constant contexts:
64 //! # #[derive(EnumSetType, Debug)] pub enum Enum { A, B, C, D, E, F, G }
65 //! const CONST_SET: EnumSet<Enum> = enum_set!(Enum::A | Enum::B);
66 //! assert_eq!(CONST_SET, Enum::A | Enum::B);
69 //! Mutable operations on the [`EnumSet`] otherwise similarly to Rust's builtin sets:
73 //! # #[derive(EnumSetType, Debug)] pub enum Enum { A, B, C, D, E, F, G }
74 //! let mut set = EnumSet::new();
75 //! set.insert(Enum::A);
76 //! set.insert_all(Enum::E | Enum::G);
77 //! assert!(set.contains(Enum::A));
78 //! assert!(!set.contains(Enum::B));
79 //! assert_eq!(set, Enum::A | Enum::E | Enum::G);
82 use core::cmp::Ordering;
84 use core::fmt::{Debug, Formatter};
85 use core::hash::{Hash, Hasher};
86 use core::iter::{FromIterator, Sum};
90 /// Everything in this module is internal API and may change at any time.
94 /// A reexport of core to allow our macros to be generic to std vs core.
95 pub use ::core as core_export;
97 /// A reexport of serde so there is no requirement to depend on serde.
98 #[cfg(feature = "serde")] pub use serde2 as serde;
100 /// The actual members of EnumSetType. Put here to avoid polluting global namespaces.
101 pub unsafe trait EnumSetTypePrivate {
102 /// The underlying type used to store the bitset.
103 type Repr: EnumSetTypeRepr;
104 /// A mask of bits that are valid in the bitset.
105 const ALL_BITS: Self::Repr;
107 /// Converts an enum of this type into its bit position.
108 fn enum_into_u32(self) -> u32;
109 /// Converts a bit position into an enum value.
110 unsafe fn enum_from_u32(val: u32) -> Self;
112 /// Serializes the `EnumSet`.
114 /// This and `deserialize` are part of the `EnumSetType` trait so the procedural derive
115 /// can control how `EnumSet` is serialized.
116 #[cfg(feature = "serde")]
117 fn serialize<S: serde::Serializer>(set: EnumSet<Self>, ser: S) -> Result<S::Ok, S::Error>
118 where Self: EnumSetType;
119 /// Deserializes the `EnumSet`.
120 #[cfg(feature = "serde")]
121 fn deserialize<'de, D: serde::Deserializer<'de>>(de: D) -> Result<EnumSet<Self>, D::Error>
122 where Self: EnumSetType;
125 use crate::__internal::EnumSetTypePrivate;
126 #[cfg(feature = "serde")] use crate::__internal::serde;
127 #[cfg(feature = "serde")] use crate::serde::{Serialize, Deserialize};
130 use crate::repr::EnumSetTypeRepr;
132 /// The procedural macro used to derive [`EnumSetType`], and allow enums to be used with
135 /// It may be used with any enum with no data fields, at most 127 variants, and no variant
136 /// discriminators larger than 127.
138 /// # Additional Impls
140 /// In addition to the implementation of `EnumSetType`, this procedural macro creates multiple
141 /// other impls that are either required for the macro to work, or make the procedural macro more
142 /// ergonomic to use.
144 /// A full list of traits implemented as is follows:
146 /// * [`Copy`], [`Clone`], [`Eq`], [`PartialEq`] implementations are created to allow `EnumSet`
147 /// to function properly. These automatic implementations may be suppressed using
148 /// `#[enumset(no_super_impls)]`, but these traits must still be implemented in another way.
149 /// * [`PartialEq`], [`Sub`], [`BitAnd`], [`BitOr`], [`BitXor`], and [`Not`] implementations are
150 /// created to allow the crate to be used more ergonomically in expressions. These automatic
151 /// implementations may be suppressed using `#[enumset(no_ops)]`.
155 /// Options are given with `#[enumset(foo)]` annotations attached to the same enum as the derive.
156 /// Multiple options may be given in the same annotation using the `#[enumset(foo, bar)]` syntax.
158 /// A full list of options is as follows:
160 /// * `#[enumset(no_super_impls)]` prevents the derive from creating implementations required for
161 /// [`EnumSet`] to function. When this attribute is specified, implementations of [`Copy`],
162 /// [`Clone`], [`Eq`], and [`PartialEq`]. This can be useful if you are using a code generator
163 /// that already derives these traits. These impls should function identically to the
164 /// automatically derived versions, or unintentional behavior may be a result.
165 /// * `#[enumset(no_ops)` prevents the derive from implementing any operator traits.
166 /// * `#[enumset(crate_name = "enumset2")]` may be used to change the name of the `enumset` crate
167 /// used in the generated code. By default enumset parses `Cargo.toml` to determine the name of
168 /// the crate, or falls back to `enumset` if it cannot be parsed.
170 /// When the `serde` feature is used, the following features may also be specified. These options
171 /// may be used (with no effect) when building without the feature enabled:
173 /// * `#[enumset(serialize_repr = "u8")]` may be used to specify the integer type used to serialize
174 /// the underlying bitset.
175 /// * `#[enumset(serialize_as_list)]` may be used to serialize the bitset as a list of enum
176 /// variants instead of an integer. This requires [`Deserialize`] and [`Serialize`] be
177 /// implemented on the enum.
178 /// * `#[enumset(serialize_deny_unknown)]` causes the generated deserializer to return an error
179 /// for unknown bits instead of silently ignoring them.
183 /// Deriving a plain EnumSetType:
186 /// # use enumset::*;
187 /// #[derive(EnumSetType)]
189 /// A, B, C, D, E, F, G,
193 /// Deriving a sparse EnumSetType:
196 /// # use enumset::*;
197 /// #[derive(EnumSetType)]
198 /// pub enum SparseEnum {
199 /// A = 10, B = 20, C = 30, D = 127,
203 /// Deriving an EnumSetType without adding ops:
206 /// # use enumset::*;
207 /// #[derive(EnumSetType)]
208 /// #[enumset(no_ops)]
209 /// pub enum NoOpsEnum {
210 /// A, B, C, D, E, F, G,
213 pub use enumset_derive::EnumSetType;
215 /// The trait used to define enum types that may be used with [`EnumSet`].
217 /// This trait must be impelmented using `#[derive(EnumSetType)]`, is not public API, and its
218 /// internal structure may change at any time with no warning.
220 /// For full documentation on the procedural derive and its options, see
221 /// [`#[derive(EnumSetType)]`](./derive.EnumSetType.html).
222 pub unsafe trait EnumSetType: Copy + Eq + EnumSetTypePrivate { }
224 /// An efficient set type for enums.
226 /// It is implemented using a bitset stored using the smallest integer that can fit all bits
227 /// in the underlying enum. In general, an enum variant with a discriminator of `n` is stored in
228 /// the nth least significant bit (corresponding with a mask of, e.g. `1 << enum as u32`).
230 /// # Numeric representation
232 /// `EnumSet` is internally implemented using integer types, and as such can be easily converted
233 /// from and to numbers.
235 /// Each bit of the underlying integer corresponds to at most one particular enum variant. If the
236 /// corresponding bit for a variant is set, it present in the set. Bits that do not correspond to
237 /// any variant are always unset.
239 /// By default, each enum variant is stored in a bit corresponding to its discriminator. An enum
240 /// variant with a discriminator of `n` is stored in the `n + 1`th least significant bit
241 /// (corresponding to a mask of e.g. `1 << enum as u32`).
245 /// When the `serde` feature is enabled, `EnumSet`s can be serialized and deserialized using
246 /// the `serde` crate. The exact serialization format can be controlled with additional attributes
247 /// on the enum type. These attributes are valid regardless of whether the `serde` feature
250 /// By default, `EnumSet`s serialize by directly writing out the underlying bitset as an integer
251 /// of the smallest type that can fit in the underlying enum. You can add a
252 /// `#[enumset(serialize_repr = "u8")]` attribute to your enum to control the integer type used
253 /// for serialization. This can be important for avoiding unintentional breaking changes when
254 /// `EnumSet`s are serialized with formats like `bincode`.
256 /// By default, unknown bits are ignored and silently removed from the bitset. To override thris
257 /// behavior, you can add a `#[enumset(serialize_deny_unknown)]` attribute. This will cause
258 /// deserialization to fail if an invalid bit is set.
260 /// In addition, the `#[enumset(serialize_as_list)]` attribute causes the `EnumSet` to be
261 /// instead serialized as a list of enum variants. This requires your enum type implement
262 /// [`Serialize`] and [`Deserialize`]. Note that this is a breaking change.
263 #[derive(Copy, Clone, PartialEq, Eq)]
265 pub struct EnumSet<T: EnumSetType> {
267 /// This is public due to the [`enum_set!`] macro.
268 /// This is **NOT** public API and may change at any time.
269 pub __priv_repr: T::Repr
271 impl <T: EnumSetType> EnumSet<T> {
272 // Returns all bits valid for the enum
274 fn all_bits() -> T::Repr {
278 /// Creates an empty `EnumSet`.
280 pub fn new() -> Self {
281 EnumSet { __priv_repr: T::Repr::empty() }
284 /// Returns an `EnumSet` containing a single element.
286 pub fn only(t: T) -> Self {
287 let mut set = Self::new();
292 /// Creates an empty `EnumSet`.
294 /// This is an alias for [`EnumSet::new`].
296 pub fn empty() -> Self {
300 /// Returns an `EnumSet` containing all valid variants of the enum.
302 pub fn all() -> Self {
303 EnumSet { __priv_repr: Self::all_bits() }
306 /// Total number of bits used by this type. Note that the actual amount of space used is
307 /// rounded up to the next highest integer type (`u8`, `u16`, `u32`, `u64`, or `u128`).
309 /// This is the same as [`EnumSet::variant_count`] except in enums with "sparse" variants.
310 /// (e.g. `enum Foo { A = 10, B = 20 }`)
312 pub fn bit_width() -> u32 {
313 T::Repr::WIDTH - T::ALL_BITS.leading_zeros()
316 /// The number of valid variants that this type can contain.
318 /// This is the same as [`EnumSet::bit_width`] except in enums with "sparse" variants.
319 /// (e.g. `enum Foo { A = 10, B = 20 }`)
321 pub fn variant_count() -> u32 {
322 T::ALL_BITS.count_ones()
325 /// Returns the number of elements in this set.
327 pub fn len(&self) -> usize {
328 self.__priv_repr.count_ones() as usize
330 /// Returns `true` if the set contains no elements.
332 pub fn is_empty(&self) -> bool {
333 self.__priv_repr.is_empty()
335 /// Removes all elements from the set.
337 pub fn clear(&mut self) {
338 self.__priv_repr = T::Repr::empty()
341 /// Returns `true` if `self` has no elements in common with `other`. This is equivalent to
342 /// checking for an empty intersection.
344 pub fn is_disjoint(&self, other: Self) -> bool {
345 (*self & other).is_empty()
347 /// Returns `true` if the set is a superset of another, i.e., `self` contains at least all the
348 /// values in `other`.
350 pub fn is_superset(&self, other: Self) -> bool {
351 (*self & other).__priv_repr == other.__priv_repr
353 /// Returns `true` if the set is a subset of another, i.e., `other` contains at least all
354 /// the values in `self`.
356 pub fn is_subset(&self, other: Self) -> bool {
357 other.is_superset(*self)
360 /// Returns a set containing any elements present in either set.
362 pub fn union(&self, other: Self) -> Self {
363 EnumSet { __priv_repr: self.__priv_repr | other.__priv_repr }
365 /// Returns a set containing every element present in both sets.
367 pub fn intersection(&self, other: Self) -> Self {
368 EnumSet { __priv_repr: self.__priv_repr & other.__priv_repr }
370 /// Returns a set containing element present in `self` but not in `other`.
372 pub fn difference(&self, other: Self) -> Self {
373 EnumSet { __priv_repr: self.__priv_repr.and_not(other.__priv_repr) }
375 /// Returns a set containing every element present in either `self` or `other`, but is not
378 pub fn symmetrical_difference(&self, other: Self) -> Self {
379 EnumSet { __priv_repr: self.__priv_repr ^ other.__priv_repr }
381 /// Returns a set containing all enum variants not in this set.
383 pub fn complement(&self) -> Self {
384 EnumSet { __priv_repr: !self.__priv_repr & Self::all_bits() }
387 /// Checks whether this set contains a value.
389 pub fn contains(&self, value: T) -> bool {
390 self.__priv_repr.has_bit(value.enum_into_u32())
393 /// Adds a value to this set.
395 /// If the set did not have this value present, `true` is returned.
397 /// If the set did have this value present, `false` is returned.
399 pub fn insert(&mut self, value: T) -> bool {
400 let contains = !self.contains(value);
401 self.__priv_repr.add_bit(value.enum_into_u32());
404 /// Removes a value from this set. Returns whether the value was present in the set.
406 pub fn remove(&mut self, value: T) -> bool {
407 let contains = self.contains(value);
408 self.__priv_repr.remove_bit(value.enum_into_u32());
412 /// Adds all elements in another set to this one.
414 pub fn insert_all(&mut self, other: Self) {
415 self.__priv_repr = self.__priv_repr | other.__priv_repr
417 /// Removes all values in another set from this one.
419 pub fn remove_all(&mut self, other: Self) {
420 self.__priv_repr = self.__priv_repr.and_not(other.__priv_repr);
423 /// Iterates the contents of the set in order from the least significant bit to the most
426 /// Note that iterator invalidation is impossible as the iterator contains a copy of this type,
427 /// rather than holding a reference to it.
428 pub fn iter(&self) -> EnumSetIter<T> {
429 EnumSetIter::new(*self)
433 /// Helper macro for generating conversion functions.
434 macro_rules! conversion_impls {
437 $underlying:ty, $underlying_str:expr,
438 $from_fn:ident $to_fn:ident $from_fn_opt:ident $to_fn_opt:ident,
439 $from:ident $try_from:ident $from_truncated:ident
440 $to:ident $try_to:ident $to_truncated:ident
443 impl <T : EnumSetType> EnumSet<T> {$(
444 #[doc = "Returns a `"]
445 #[doc = $underlying_str]
446 #[doc = "` representing the elements of this set.\n\nIf the underlying bitset will \
448 #[doc = $underlying_str]
449 #[doc = "` or contains bits that do not correspond to an enum variant, this method \
452 pub fn $to(&self) -> $underlying {
453 self.$try_to().expect("Bitset will not fit into this type.")
456 #[doc = "Tries to return a `"]
457 #[doc = $underlying_str]
458 #[doc = "` representing the elements of this set.\n\nIf the underlying bitset will \
460 #[doc = $underlying_str]
461 #[doc = "` or contains bits that do not correspond to an enum variant, this method \
462 will instead return `None`."]
464 pub fn $try_to(&self) -> Option<$underlying> {
465 EnumSetTypeRepr::$to_fn_opt(&self.__priv_repr)
468 #[doc = "Returns a truncated `"]
469 #[doc = $underlying_str]
470 #[doc = "` representing the elements of this set.\n\nIf the underlying bitset will \
472 #[doc = $underlying_str]
473 #[doc = "`, this method will truncate any bits that don't fit or do not correspond \
474 to an enum variant."]
476 pub fn $to_truncated(&self) -> $underlying {
477 EnumSetTypeRepr::$to_fn(&self.__priv_repr)
480 #[doc = "Constructs a bitset from a `"]
481 #[doc = $underlying_str]
482 #[doc = "`.\n\nIf a bit that doesn't correspond to an enum variant is set, this \
485 pub fn $from(bits: $underlying) -> Self {
486 Self::$try_from(bits).expect("Bitset contains invalid variants.")
489 #[doc = "Attempts to constructs a bitset from a `"]
490 #[doc = $underlying_str]
491 #[doc = "`.\n\nIf a bit that doesn't correspond to an enum variant is set, this \
492 method will return `None`."]
494 pub fn $try_from(bits: $underlying) -> Option<Self> {
495 let bits = T::Repr::$from_fn_opt(bits);
496 let mask = Self::all().__priv_repr;
497 bits.and_then(|bits| if bits.and_not(mask).is_empty() {
498 Some(EnumSet { __priv_repr: bits })
504 #[doc = "Constructs a bitset from a `"]
505 #[doc = $underlying_str]
506 #[doc = "`, ignoring invalid variants."]
508 pub fn $from_truncated(bits: $underlying) -> Self {
509 let mask = Self::all().$to_truncated();
510 let bits = <T::Repr as EnumSetTypeRepr>::$from_fn(bits & mask);
511 EnumSet { __priv_repr: bits }
517 for_num!(u8, "u8", from_u8 to_u8 from_u8_opt to_u8_opt,
518 from_u8 try_from_u8 from_u8_truncated as_u8 try_as_u8 as_u8_truncated);
519 for_num!(u16, "u16", from_u16 to_u16 from_u16_opt to_u16_opt,
520 from_u16 try_from_u16 from_u16_truncated as_u16 try_as_u16 as_u16_truncated);
521 for_num!(u32, "u32", from_u32 to_u32 from_u32_opt to_u32_opt,
522 from_u32 try_from_u32 from_u32_truncated as_u32 try_as_u32 as_u32_truncated);
523 for_num!(u64, "u64", from_u64 to_u64 from_u64_opt to_u64_opt,
524 from_u64 try_from_u64 from_u64_truncated as_u64 try_as_u64 as_u64_truncated);
525 for_num!(u128, "u128", from_u128 to_u128 from_u128_opt to_u128_opt,
526 from_u128 try_from_u128 from_u128_truncated as_u128 try_as_u128 as_u128_truncated);
527 for_num!(usize, "usize", from_usize to_usize from_usize_opt to_usize_opt,
528 from_usize try_from_usize from_usize_truncated
529 as_usize try_as_usize as_usize_truncated);
532 impl <T: EnumSetType> Default for EnumSet<T> {
533 /// Returns an empty set.
534 fn default() -> Self {
539 impl <T: EnumSetType> IntoIterator for EnumSet<T> {
541 type IntoIter = EnumSetIter<T>;
543 fn into_iter(self) -> Self::IntoIter {
547 impl <T: EnumSetType> Sum for EnumSet<T> {
548 fn sum<I: Iterator<Item=Self>>(iter: I) -> Self {
549 iter.fold(EnumSet::empty(), |a, v| a | v)
552 impl <'a, T: EnumSetType> Sum<&'a EnumSet<T>> for EnumSet<T> {
553 fn sum<I: Iterator<Item=&'a Self>>(iter: I) -> Self {
554 iter.fold(EnumSet::empty(), |a, v| a | *v)
557 impl <T: EnumSetType> Sum<T> for EnumSet<T> {
558 fn sum<I: Iterator<Item=T>>(iter: I) -> Self {
559 iter.fold(EnumSet::empty(), |a, v| a | v)
562 impl <'a, T: EnumSetType> Sum<&'a T> for EnumSet<T> {
563 fn sum<I: Iterator<Item=&'a T>>(iter: I) -> Self {
564 iter.fold(EnumSet::empty(), |a, v| a | *v)
568 impl <T: EnumSetType, O: Into<EnumSet<T>>> Sub<O> for EnumSet<T> {
571 fn sub(self, other: O) -> Self::Output {
572 self.difference(other.into())
575 impl <T: EnumSetType, O: Into<EnumSet<T>>> BitAnd<O> for EnumSet<T> {
578 fn bitand(self, other: O) -> Self::Output {
579 self.intersection(other.into())
582 impl <T: EnumSetType, O: Into<EnumSet<T>>> BitOr<O> for EnumSet<T> {
585 fn bitor(self, other: O) -> Self::Output {
586 self.union(other.into())
589 impl <T: EnumSetType, O: Into<EnumSet<T>>> BitXor<O> for EnumSet<T> {
592 fn bitxor(self, other: O) -> Self::Output {
593 self.symmetrical_difference(other.into())
597 impl <T: EnumSetType, O: Into<EnumSet<T>>> SubAssign<O> for EnumSet<T> {
599 fn sub_assign(&mut self, rhs: O) {
603 impl <T: EnumSetType, O: Into<EnumSet<T>>> BitAndAssign<O> for EnumSet<T> {
605 fn bitand_assign(&mut self, rhs: O) {
609 impl <T: EnumSetType, O: Into<EnumSet<T>>> BitOrAssign<O> for EnumSet<T> {
611 fn bitor_assign(&mut self, rhs: O) {
615 impl <T: EnumSetType, O: Into<EnumSet<T>>> BitXorAssign<O> for EnumSet<T> {
617 fn bitxor_assign(&mut self, rhs: O) {
622 impl <T: EnumSetType> Not for EnumSet<T> {
625 fn not(self) -> Self::Output {
630 impl <T: EnumSetType> From<T> for EnumSet<T> {
631 fn from(t: T) -> Self {
636 impl <T: EnumSetType> PartialEq<T> for EnumSet<T> {
637 fn eq(&self, other: &T) -> bool {
638 self.__priv_repr == EnumSet::only(*other).__priv_repr
641 impl <T: EnumSetType + Debug> Debug for EnumSet<T> {
642 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
643 let mut is_first = true;
644 f.write_str("EnumSet(")?;
645 for v in self.iter() {
646 if !is_first { f.write_str(" | ")?; }
655 #[allow(clippy::derive_hash_xor_eq)] // This impl exists to change trait bounds only.
656 impl <T: EnumSetType> Hash for EnumSet<T> {
657 fn hash<H: Hasher>(&self, state: &mut H) {
658 self.__priv_repr.hash(state)
661 impl <T: EnumSetType> PartialOrd for EnumSet<T> {
662 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
663 self.__priv_repr.partial_cmp(&other.__priv_repr)
666 impl <T: EnumSetType> Ord for EnumSet<T> {
667 fn cmp(&self, other: &Self) -> Ordering {
668 self.__priv_repr.cmp(&other.__priv_repr)
672 #[cfg(feature = "serde")]
673 impl <T: EnumSetType> Serialize for EnumSet<T> {
674 fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
675 T::serialize(*self, serializer)
679 #[cfg(feature = "serde")]
680 impl <'de, T: EnumSetType> Deserialize<'de> for EnumSet<T> {
681 fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
682 T::deserialize(deserializer)
686 /// The iterator used by [`EnumSet`]s.
687 #[derive(Clone, Debug)]
688 pub struct EnumSetIter<T: EnumSetType> {
691 impl <T: EnumSetType> EnumSetIter<T> {
692 fn new(set: EnumSet<T>) -> EnumSetIter<T> {
697 impl <T: EnumSetType> Iterator for EnumSetIter<T> {
700 fn next(&mut self) -> Option<Self::Item> {
701 if self.set.is_empty() {
704 let bit = self.set.__priv_repr.trailing_zeros();
705 self.set.__priv_repr.remove_bit(bit);
706 unsafe { Some(T::enum_from_u32(bit)) }
709 fn size_hint(&self) -> (usize, Option<usize>) {
710 let left = self.set.len();
715 impl <T: EnumSetType> DoubleEndedIterator for EnumSetIter<T> {
716 fn next_back(&mut self) -> Option<Self::Item> {
717 if self.set.is_empty() {
720 let bit = T::Repr::WIDTH - 1 - self.set.__priv_repr.leading_zeros();
721 self.set.__priv_repr.remove_bit(bit);
722 unsafe { Some(T::enum_from_u32(bit)) }
727 impl<T: EnumSetType> ExactSizeIterator for EnumSetIter<T> {}
729 impl<T: EnumSetType> Extend<T> for EnumSet<T> {
730 fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I) {
731 iter.into_iter().for_each(|v| { self.insert(v); });
735 impl<T: EnumSetType> FromIterator<T> for EnumSet<T> {
736 fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self {
737 let mut set = EnumSet::default();
743 impl<T: EnumSetType> Extend<EnumSet<T>> for EnumSet<T> {
744 fn extend<I: IntoIterator<Item = EnumSet<T>>>(&mut self, iter: I) {
745 iter.into_iter().for_each(|v| { self.insert_all(v); });
749 impl<T: EnumSetType> FromIterator<EnumSet<T>> for EnumSet<T> {
750 fn from_iter<I: IntoIterator<Item = EnumSet<T>>>(iter: I) -> Self {
751 let mut set = EnumSet::default();
757 /// Creates a EnumSet literal, which can be used in const contexts.
759 /// The syntax used is `enum_set!(Type::A | Type::B | Type::C)`. Each variant must be of the same
760 /// type, or a error will occur at compile-time.
762 /// This macro accepts trailing `|`s to allow easier use in other macros.
767 /// # use enumset::*;
768 /// # #[derive(EnumSetType, Debug)] enum Enum { A, B, C }
769 /// const CONST_SET: EnumSet<Enum> = enum_set!(Enum::A | Enum::B);
770 /// assert_eq!(CONST_SET, Enum::A | Enum::B);
773 /// This macro is strongly typed. For example, the following will not compile:
776 /// # use enumset::*;
777 /// # #[derive(EnumSetType, Debug)] enum Enum { A, B, C }
778 /// # #[derive(EnumSetType, Debug)] enum Enum2 { A, B, C }
779 /// let type_error = enum_set!(Enum::A | Enum2::B);
782 macro_rules! enum_set {
784 $crate::EnumSet { __priv_repr: 0 }
786 ($value:path $(|)*) => {
788 #[allow(deprecated)] let value = $value.__impl_enumset_internal__const_only();
792 ($value:path | $($rest:path)|* $(|)*) => {
794 #[allow(deprecated)] let value = $value.__impl_enumset_internal__const_only();
795 $(#[allow(deprecated)] let value = $rest.__impl_enumset_internal__const_merge(value);)*