2 #![forbid(missing_docs)]
3 // The safety requirement is "use the procedural derive".
4 #![allow(clippy::missing_safety_doc)]
6 //! A library for defining enums that can be used in compact bit sets. It supports enums up to 128
7 //! variants, and has a macro to use these sets in constants.
9 //! For serde support, enable the `serde` feature.
11 //! # Defining enums for use with EnumSet
13 //! Enums to be used with [`EnumSet`] should be defined using `#[derive(EnumSetType)]`:
17 //! #[derive(EnumSetType, Debug)]
19 //! A, B, C, D, E, F, G,
23 //! For more information on more advanced use cases, see the documentation for
24 //! [`#[derive(EnumSetType)]`](./derive.EnumSetType.html).
26 //! # Working with EnumSets
28 //! EnumSets can be constructed via [`EnumSet::new()`] like a normal set. In addition,
29 //! `#[derive(EnumSetType)]` creates operator overloads that allow you to create EnumSets like so:
33 //! # #[derive(EnumSetType, Debug)] pub enum Enum { A, B, C, D, E, F, G }
34 //! let new_set = Enum::A | Enum::C | Enum::G;
35 //! assert_eq!(new_set.len(), 3);
38 //! All bitwise operations you would expect to work on bitsets also work on both EnumSets and
39 //! enums with `#[derive(EnumSetType)]`:
42 //! # #[derive(EnumSetType, Debug)] pub enum Enum { A, B, C, D, E, F, G }
43 //! // Intersection of sets
44 //! assert_eq!((Enum::A | Enum::B) & Enum::C, EnumSet::empty());
45 //! assert_eq!((Enum::A | Enum::B) & Enum::A, Enum::A);
46 //! assert_eq!(Enum::A & Enum::B, EnumSet::empty());
48 //! // Symmetric difference of sets
49 //! assert_eq!((Enum::A | Enum::B) ^ (Enum::B | Enum::C), Enum::A | Enum::C);
50 //! assert_eq!(Enum::A ^ Enum::C, Enum::A | Enum::C);
52 //! // Difference of sets
53 //! assert_eq!((Enum::A | Enum::B | Enum::C) - Enum::B, Enum::A | Enum::C);
55 //! // Complement of sets
56 //! assert_eq!(!(Enum::E | Enum::G), Enum::A | Enum::B | Enum::C | Enum::D | Enum::F);
59 //! The [`enum_set!`] macro allows you to create EnumSets in constant contexts:
63 //! # #[derive(EnumSetType, Debug)] pub enum Enum { A, B, C, D, E, F, G }
64 //! const CONST_SET: EnumSet<Enum> = enum_set!(Enum::A | Enum::B);
65 //! assert_eq!(CONST_SET, Enum::A | Enum::B);
68 //! Mutable operations on the [`EnumSet`] otherwise similarly to Rust's builtin sets:
72 //! # #[derive(EnumSetType, Debug)] pub enum Enum { A, B, C, D, E, F, G }
73 //! let mut set = EnumSet::new();
74 //! set.insert(Enum::A);
75 //! set.insert_all(Enum::E | Enum::G);
76 //! assert!(set.contains(Enum::A));
77 //! assert!(!set.contains(Enum::B));
78 //! assert_eq!(set, Enum::A | Enum::E | Enum::G);
81 use core::cmp::Ordering;
83 use core::fmt::{Debug, Formatter};
84 use core::hash::{Hash, Hasher};
85 use core::iter::{FromIterator, Sum};
89 /// Everything in this module is internal API and may change at any time.
93 /// A reexport of core to allow our macros to be generic to std vs core.
94 pub use ::core as core_export;
96 /// A reexport of serde so there is no requirement to depend on serde.
97 #[cfg(feature = "serde")]
98 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 #[cfg(feature = "serde")]
126 use crate::__internal::serde;
127 use crate::__internal::EnumSetTypePrivate;
128 #[cfg(feature = "serde")]
129 use crate::serde::{Deserialize, Serialize};
132 use crate::repr::EnumSetTypeRepr;
134 /// The procedural macro used to derive [`EnumSetType`], and allow enums to be used with
137 /// It may be used with any enum with no data fields, at most 127 variants, and no variant
138 /// discriminators larger than 127.
140 /// # Additional Impls
142 /// In addition to the implementation of `EnumSetType`, this procedural macro creates multiple
143 /// other impls that are either required for the macro to work, or make the procedural macro more
144 /// ergonomic to use.
146 /// A full list of traits implemented as is follows:
148 /// * [`Copy`], [`Clone`], [`Eq`], [`PartialEq`] implementations are created to allow `EnumSet`
149 /// to function properly. These automatic implementations may be suppressed using
150 /// `#[enumset(no_super_impls)]`, but these traits must still be implemented in another way.
151 /// * [`PartialEq`], [`Sub`], [`BitAnd`], [`BitOr`], [`BitXor`], and [`Not`] implementations are
152 /// created to allow the crate to be used more ergonomically in expressions. These automatic
153 /// implementations may be suppressed using `#[enumset(no_ops)]`.
157 /// Options are given with `#[enumset(foo)]` annotations attached to the same enum as the derive.
158 /// Multiple options may be given in the same annotation using the `#[enumset(foo, bar)]` syntax.
160 /// A full list of options is as follows:
162 /// * `#[enumset(no_super_impls)]` prevents the derive from creating implementations required for
163 /// [`EnumSet`] to function. When this attribute is specified, implementations of [`Copy`],
164 /// [`Clone`], [`Eq`], and [`PartialEq`]. This can be useful if you are using a code generator
165 /// that already derives these traits. These impls should function identically to the
166 /// automatically derived versions, or unintentional behavior may be a result.
167 /// * `#[enumset(no_ops)` prevents the derive from implementing any operator traits.
168 /// * `#[enumset(crate_name = "enumset2")]` may be used to change the name of the `enumset` crate
169 /// used in the generated code. When the `std` feature is enabled, enumset parses `Cargo.toml`
170 /// to determine the name of the crate, and this flag is unnecessary.
171 /// * `#[enumset(repr = "u8")]` may be used to specify the in-memory representation of `EnumSet`s
172 /// of this enum type. The effects of this are described in [the `EnumSet` documentation under
173 /// “FFI, Safety and `repr`”][EnumSet#ffi-safety-and-repr]. Allowed types are `u8`, `u16`, `u32`,
174 /// `u64` and `u128`. If this is not used, then the derive macro will choose a type to best fit
175 /// the enum, but there are no guarantees about which type will be chosen.
177 /// When the `serde` feature is used, the following features may also be specified. These options
178 /// may be used (with no effect) when building without the feature enabled:
180 /// * `#[enumset(serialize_repr = "u8")]` may be used to specify the integer type used to serialize
181 /// the underlying bitset.
182 /// * `#[enumset(serialize_as_list)]` may be used to serialize the bitset as a list of enum
183 /// variants instead of an integer. This requires [`Deserialize`] and [`Serialize`] be
184 /// implemented on the enum.
185 /// * `#[enumset(serialize_deny_unknown)]` causes the generated deserializer to return an error
186 /// for unknown bits instead of silently ignoring them.
190 /// Deriving a plain EnumSetType:
193 /// # use enumset::*;
194 /// #[derive(EnumSetType)]
196 /// A, B, C, D, E, F, G,
200 /// Deriving a sparse EnumSetType:
203 /// # use enumset::*;
204 /// #[derive(EnumSetType)]
205 /// pub enum SparseEnum {
206 /// A = 10, B = 20, C = 30, D = 127,
210 /// Deriving an EnumSetType without adding ops:
213 /// # use enumset::*;
214 /// #[derive(EnumSetType)]
215 /// #[enumset(no_ops)]
216 /// pub enum NoOpsEnum {
217 /// A, B, C, D, E, F, G,
220 pub use enumset_derive::EnumSetType;
222 /// The trait used to define enum types that may be used with [`EnumSet`].
224 /// This trait must be impelmented using `#[derive(EnumSetType)]`, is not public API, and its
225 /// internal structure may change at any time with no warning.
227 /// For full documentation on the procedural derive and its options, see
228 /// [`#[derive(EnumSetType)]`](./derive.EnumSetType.html).
229 pub unsafe trait EnumSetType: Copy + Eq + EnumSetTypePrivate {}
231 /// An [`EnumSetType`] for which [`EnumSet`]s have a guaranteed in-memory representation.
233 /// An implementation of this trait is generated by using
234 /// [`#[derive(EnumSetType)]`](./derive.EnumSetType.html) with the annotation
235 /// `#[enumset(repr = "…")]`, where `…` is `u8`, `u16`, `u32`, `u64` or `u128`.
237 /// For any type `T` that implements this trait, the in-memory representation of `EnumSet<T>`
238 /// is guaranteed to be `Repr`. This guarantee is useful for FFI. See [the `EnumSet` documentation
239 /// under “FFI, Safety and `repr`”][EnumSet#ffi-safety-and-repr] for an example.
240 pub unsafe trait EnumSetTypeWithRepr:
241 EnumSetType + EnumSetTypePrivate<Repr = <Self as EnumSetTypeWithRepr>::Repr>
243 /// The guaranteed representation.
244 type Repr: EnumSetTypeRepr;
247 /// An efficient set type for enums.
249 /// It is implemented using a bitset stored using the smallest integer that can fit all bits
250 /// in the underlying enum. In general, an enum variant with a discriminator of `n` is stored in
251 /// the nth least significant bit (corresponding with a mask of, e.g. `1 << enum as u32`).
253 /// # Numeric representation
255 /// `EnumSet` is internally implemented using integer types, and as such can be easily converted
256 /// from and to numbers.
258 /// Each bit of the underlying integer corresponds to at most one particular enum variant. If the
259 /// corresponding bit for a variant is set, it present in the set. Bits that do not correspond to
260 /// any variant are always unset.
262 /// By default, each enum variant is stored in a bit corresponding to its discriminator. An enum
263 /// variant with a discriminator of `n` is stored in the `n + 1`th least significant bit
264 /// (corresponding to a mask of e.g. `1 << enum as u32`).
268 /// When the `serde` feature is enabled, `EnumSet`s can be serialized and deserialized using
269 /// the `serde` crate. The exact serialization format can be controlled with additional attributes
270 /// on the enum type. These attributes are valid regardless of whether the `serde` feature
273 /// By default, `EnumSet`s serialize by directly writing out the underlying bitset as an integer
274 /// of the smallest type that can fit in the underlying enum. You can add a
275 /// `#[enumset(serialize_repr = "u8")]` attribute to your enum to control the integer type used
276 /// for serialization. This can be important for avoiding unintentional breaking changes when
277 /// `EnumSet`s are serialized with formats like `bincode`.
279 /// By default, unknown bits are ignored and silently removed from the bitset. To override thris
280 /// behavior, you can add a `#[enumset(serialize_deny_unknown)]` attribute. This will cause
281 /// deserialization to fail if an invalid bit is set.
283 /// In addition, the `#[enumset(serialize_as_list)]` attribute causes the `EnumSet` to be
284 /// instead serialized as a list of enum variants. This requires your enum type implement
285 /// [`Serialize`] and [`Deserialize`]. Note that this is a breaking change.
287 /// # FFI, Safety and `repr`
289 /// If an enum type `T` is annotated with [`#[enumset(repr = "R")]`][derive@EnumSetType#options],
290 /// then several things happen:
292 /// * `T` will implement <code>[EnumSetTypeWithRepr]<Repr = R></code> in addition to
294 /// * The `EnumSet` methods with `repr` in their name, such as [`as_repr`][EnumSet::as_repr] and
295 /// [`from_repr`][EnumSet::from_repr], will be available for `EnumSet<T>`.
296 /// * The in-memory representation of `EnumSet<T>` is guaranteed to be `R`.
298 /// That last guarantee makes it sound to send `EnumSet<T>` across an FFI boundary. For example:
301 /// # use enumset::*;
304 /// # // This example “foreign” function is actually written in Rust, but for the sake
305 /// # // of example, we'll pretend it's written in C.
307 /// # extern "C" fn some_foreign_function(set: u32) -> u32 {
313 /// // This function is written in C like:
314 /// // uint32_t some_foreign_function(uint32_t set) { … }
315 /// fn some_foreign_function(set: EnumSet<MyEnum>) -> EnumSet<MyEnum>;
318 /// #[derive(Debug, EnumSetType)]
319 /// #[enumset(repr = "u32")]
320 /// enum MyEnum { A, B, C }
322 /// let set: EnumSet<MyEnum> = enum_set!(MyEnum::A | MyEnum::C);
324 /// let new_set: EnumSet<MyEnum> = unsafe { some_foreign_function(set) };
325 /// assert_eq!(new_set, enum_set!(MyEnum::C));
328 /// When an `EnumSet<T>` is received via FFI, all bits that don't correspond to an enum variant
329 /// of `T` must be set to 0. Behavior is **undefined** if any of these bits are set to 1.
330 #[derive(Copy, Clone, PartialEq, Eq)]
332 pub struct EnumSet<T: EnumSetType> {
334 /// This is public due to the [`enum_set!`] macro.
335 /// This is **NOT** public API and may change at any time.
336 pub __priv_repr: T::Repr,
338 impl<T: EnumSetType> EnumSet<T> {
339 // Returns all bits valid for the enum
341 fn all_bits() -> T::Repr {
345 /// Creates an empty `EnumSet`.
347 pub fn new() -> Self {
348 EnumSet { __priv_repr: T::Repr::empty() }
351 /// Returns an `EnumSet` containing a single element.
353 pub fn only(t: T) -> Self {
354 let mut set = Self::new();
359 /// Creates an empty `EnumSet`.
361 /// This is an alias for [`EnumSet::new`].
363 pub fn empty() -> Self {
367 /// Returns an `EnumSet` containing all valid variants of the enum.
369 pub fn all() -> Self {
370 EnumSet { __priv_repr: Self::all_bits() }
373 /// Total number of bits used by this type. Note that the actual amount of space used is
374 /// rounded up to the next highest integer type (`u8`, `u16`, `u32`, `u64`, or `u128`).
376 /// This is the same as [`EnumSet::variant_count`] except in enums with "sparse" variants.
377 /// (e.g. `enum Foo { A = 10, B = 20 }`)
379 pub fn bit_width() -> u32 {
380 T::Repr::WIDTH - T::ALL_BITS.leading_zeros()
383 /// The number of valid variants that this type can contain.
385 /// This is the same as [`EnumSet::bit_width`] except in enums with "sparse" variants.
386 /// (e.g. `enum Foo { A = 10, B = 20 }`)
388 pub fn variant_count() -> u32 {
389 T::ALL_BITS.count_ones()
392 /// Returns the number of elements in this set.
394 pub fn len(&self) -> usize {
395 self.__priv_repr.count_ones() as usize
397 /// Returns `true` if the set contains no elements.
399 pub fn is_empty(&self) -> bool {
400 self.__priv_repr.is_empty()
402 /// Removes all elements from the set.
404 pub fn clear(&mut self) {
405 self.__priv_repr = T::Repr::empty()
408 /// Returns `true` if `self` has no elements in common with `other`. This is equivalent to
409 /// checking for an empty intersection.
411 pub fn is_disjoint(&self, other: Self) -> bool {
412 (*self & other).is_empty()
414 /// Returns `true` if the set is a superset of another, i.e., `self` contains at least all the
415 /// values in `other`.
417 pub fn is_superset(&self, other: Self) -> bool {
418 (*self & other).__priv_repr == other.__priv_repr
420 /// Returns `true` if the set is a subset of another, i.e., `other` contains at least all
421 /// the values in `self`.
423 pub fn is_subset(&self, other: Self) -> bool {
424 other.is_superset(*self)
427 /// Returns a set containing any elements present in either set.
429 pub fn union(&self, other: Self) -> Self {
430 EnumSet { __priv_repr: self.__priv_repr | other.__priv_repr }
432 /// Returns a set containing every element present in both sets.
434 pub fn intersection(&self, other: Self) -> Self {
435 EnumSet { __priv_repr: self.__priv_repr & other.__priv_repr }
437 /// Returns a set containing element present in `self` but not in `other`.
439 pub fn difference(&self, other: Self) -> Self {
440 EnumSet { __priv_repr: self.__priv_repr.and_not(other.__priv_repr) }
442 /// Returns a set containing every element present in either `self` or `other`, but is not
445 pub fn symmetrical_difference(&self, other: Self) -> Self {
446 EnumSet { __priv_repr: self.__priv_repr ^ other.__priv_repr }
448 /// Returns a set containing all enum variants not in this set.
450 pub fn complement(&self) -> Self {
451 EnumSet { __priv_repr: !self.__priv_repr & Self::all_bits() }
454 /// Checks whether this set contains a value.
456 pub fn contains(&self, value: T) -> bool {
457 self.__priv_repr.has_bit(value.enum_into_u32())
460 /// Adds a value to this set.
462 /// If the set did not have this value present, `true` is returned.
464 /// If the set did have this value present, `false` is returned.
466 pub fn insert(&mut self, value: T) -> bool {
467 let contains = !self.contains(value);
468 self.__priv_repr.add_bit(value.enum_into_u32());
471 /// Removes a value from this set. Returns whether the value was present in the set.
473 pub fn remove(&mut self, value: T) -> bool {
474 let contains = self.contains(value);
475 self.__priv_repr.remove_bit(value.enum_into_u32());
479 /// Adds all elements in another set to this one.
481 pub fn insert_all(&mut self, other: Self) {
482 self.__priv_repr = self.__priv_repr | other.__priv_repr
484 /// Removes all values in another set from this one.
486 pub fn remove_all(&mut self, other: Self) {
487 self.__priv_repr = self.__priv_repr.and_not(other.__priv_repr);
490 /// Iterates the contents of the set in order from the least significant bit to the most
493 /// Note that iterator invalidation is impossible as the iterator contains a copy of this type,
494 /// rather than holding a reference to it.
495 pub fn iter(&self) -> EnumSetIter<T> {
496 EnumSetIter::new(*self)
499 /// Returns a `T::Repr` representing the elements of this set.
501 /// Unlike the other `as_*` methods, this method is zero-cost and guaranteed not to fail,
502 /// panic or truncate any bits.
504 /// In order to use this method, the definition of `T` must have the `#[enumset(repr = "…")]`
507 pub fn as_repr(&self) -> <T as EnumSetTypeWithRepr>::Repr
508 where T: EnumSetTypeWithRepr {
512 /// Constructs a bitset from a `T::Repr` without checking for invalid bits.
514 /// Unlike the other `from_*` methods, this method is zero-cost and guaranteed not to fail,
515 /// panic or truncate any bits, provided the conditions under “Safety” are upheld.
517 /// In order to use this method, the definition of `T` must have the `#[enumset(repr = "…")]`
522 /// All bits in the provided parameter `bits` that don't correspond to an enum variant of
523 /// `T` must be set to 0. Behavior is **undefined** if any of these bits are set to 1.
525 pub unsafe fn from_repr_unchecked(bits: <T as EnumSetTypeWithRepr>::Repr) -> Self
526 where T: EnumSetTypeWithRepr {
527 Self { __priv_repr: bits }
530 /// Constructs a bitset from a `T::Repr`.
532 /// If a bit that doesn't correspond to an enum variant is set, this
533 /// method will panic.
535 /// In order to use this method, the definition of `T` must have the `#[enumset(repr = "…")]`
538 pub fn from_repr(bits: <T as EnumSetTypeWithRepr>::Repr) -> Self
539 where T: EnumSetTypeWithRepr {
540 Self::try_from_repr(bits).expect("Bitset contains invalid variants.")
543 /// Attempts to constructs a bitset from a `T::Repr`.
545 /// If a bit that doesn't correspond to an enum variant is set, this
546 /// method will return `None`.
548 /// In order to use this method, the definition of `T` must have the `#[enumset(repr = "…")]`
551 pub fn try_from_repr(bits: <T as EnumSetTypeWithRepr>::Repr) -> Option<Self>
552 where T: EnumSetTypeWithRepr {
553 let mask = Self::all().__priv_repr;
554 if bits.and_not(mask).is_empty() {
555 Some(EnumSet { __priv_repr: bits })
561 /// Constructs a bitset from a `T::Repr`, ignoring invalid variants.
563 /// In order to use this method, the definition of `T` must have the `#[enumset(repr = "…")]`
566 pub fn from_repr_truncated(bits: <T as EnumSetTypeWithRepr>::Repr) -> Self
567 where T: EnumSetTypeWithRepr {
568 let mask = Self::all().as_repr();
569 let bits = bits & mask;
570 EnumSet { __priv_repr: bits }
574 /// Helper macro for generating conversion functions.
575 macro_rules! conversion_impls {
578 $underlying:ty, $underlying_str:expr,
579 $from_fn:ident $to_fn:ident $from_fn_opt:ident $to_fn_opt:ident,
580 $from:ident $try_from:ident $from_truncated:ident
581 $to:ident $try_to:ident $to_truncated:ident
584 impl <T : EnumSetType> EnumSet<T> {$(
585 #[doc = "Returns a `"]
586 #[doc = $underlying_str]
587 #[doc = "` representing the elements of this set.\n\nIf the underlying bitset will \
589 #[doc = $underlying_str]
590 #[doc = "` or contains bits that do not correspond to an enum variant, this method \
593 pub fn $to(&self) -> $underlying {
594 self.$try_to().expect("Bitset will not fit into this type.")
597 #[doc = "Tries to return a `"]
598 #[doc = $underlying_str]
599 #[doc = "` representing the elements of this set.\n\nIf the underlying bitset will \
601 #[doc = $underlying_str]
602 #[doc = "` or contains bits that do not correspond to an enum variant, this method \
603 will instead return `None`."]
605 pub fn $try_to(&self) -> Option<$underlying> {
606 EnumSetTypeRepr::$to_fn_opt(&self.__priv_repr)
609 #[doc = "Returns a truncated `"]
610 #[doc = $underlying_str]
611 #[doc = "` representing the elements of this set.\n\nIf the underlying bitset will \
613 #[doc = $underlying_str]
614 #[doc = "`, this method will truncate any bits that don't fit or do not correspond \
615 to an enum variant."]
617 pub fn $to_truncated(&self) -> $underlying {
618 EnumSetTypeRepr::$to_fn(&self.__priv_repr)
621 #[doc = "Constructs a bitset from a `"]
622 #[doc = $underlying_str]
623 #[doc = "`.\n\nIf a bit that doesn't correspond to an enum variant is set, this \
626 pub fn $from(bits: $underlying) -> Self {
627 Self::$try_from(bits).expect("Bitset contains invalid variants.")
630 #[doc = "Attempts to constructs a bitset from a `"]
631 #[doc = $underlying_str]
632 #[doc = "`.\n\nIf a bit that doesn't correspond to an enum variant is set, this \
633 method will return `None`."]
635 pub fn $try_from(bits: $underlying) -> Option<Self> {
636 let bits = T::Repr::$from_fn_opt(bits);
637 let mask = Self::all().__priv_repr;
638 bits.and_then(|bits| if bits.and_not(mask).is_empty() {
639 Some(EnumSet { __priv_repr: bits })
645 #[doc = "Constructs a bitset from a `"]
646 #[doc = $underlying_str]
647 #[doc = "`, ignoring invalid variants."]
649 pub fn $from_truncated(bits: $underlying) -> Self {
650 let mask = Self::all().$to_truncated();
651 let bits = <T::Repr as EnumSetTypeRepr>::$from_fn(bits & mask);
652 EnumSet { __priv_repr: bits }
658 for_num!(u8, "u8", from_u8 to_u8 from_u8_opt to_u8_opt,
659 from_u8 try_from_u8 from_u8_truncated as_u8 try_as_u8 as_u8_truncated);
660 for_num!(u16, "u16", from_u16 to_u16 from_u16_opt to_u16_opt,
661 from_u16 try_from_u16 from_u16_truncated as_u16 try_as_u16 as_u16_truncated);
662 for_num!(u32, "u32", from_u32 to_u32 from_u32_opt to_u32_opt,
663 from_u32 try_from_u32 from_u32_truncated as_u32 try_as_u32 as_u32_truncated);
664 for_num!(u64, "u64", from_u64 to_u64 from_u64_opt to_u64_opt,
665 from_u64 try_from_u64 from_u64_truncated as_u64 try_as_u64 as_u64_truncated);
666 for_num!(u128, "u128", from_u128 to_u128 from_u128_opt to_u128_opt,
667 from_u128 try_from_u128 from_u128_truncated as_u128 try_as_u128 as_u128_truncated);
668 for_num!(usize, "usize", from_usize to_usize from_usize_opt to_usize_opt,
669 from_usize try_from_usize from_usize_truncated
670 as_usize try_as_usize as_usize_truncated);
673 impl<T: EnumSetType> Default for EnumSet<T> {
674 /// Returns an empty set.
675 fn default() -> Self {
680 impl<T: EnumSetType> IntoIterator for EnumSet<T> {
682 type IntoIter = EnumSetIter<T>;
684 fn into_iter(self) -> Self::IntoIter {
688 impl<T: EnumSetType> Sum for EnumSet<T> {
689 fn sum<I: Iterator<Item = Self>>(iter: I) -> Self {
690 iter.fold(EnumSet::empty(), |a, v| a | v)
693 impl<'a, T: EnumSetType> Sum<&'a EnumSet<T>> for EnumSet<T> {
694 fn sum<I: Iterator<Item = &'a Self>>(iter: I) -> Self {
695 iter.fold(EnumSet::empty(), |a, v| a | *v)
698 impl<T: EnumSetType> Sum<T> for EnumSet<T> {
699 fn sum<I: Iterator<Item = T>>(iter: I) -> Self {
700 iter.fold(EnumSet::empty(), |a, v| a | v)
703 impl<'a, T: EnumSetType> Sum<&'a T> for EnumSet<T> {
704 fn sum<I: Iterator<Item = &'a T>>(iter: I) -> Self {
705 iter.fold(EnumSet::empty(), |a, v| a | *v)
709 impl<T: EnumSetType, O: Into<EnumSet<T>>> Sub<O> for EnumSet<T> {
712 fn sub(self, other: O) -> Self::Output {
713 self.difference(other.into())
716 impl<T: EnumSetType, O: Into<EnumSet<T>>> BitAnd<O> for EnumSet<T> {
719 fn bitand(self, other: O) -> Self::Output {
720 self.intersection(other.into())
723 impl<T: EnumSetType, O: Into<EnumSet<T>>> BitOr<O> for EnumSet<T> {
726 fn bitor(self, other: O) -> Self::Output {
727 self.union(other.into())
730 impl<T: EnumSetType, O: Into<EnumSet<T>>> BitXor<O> for EnumSet<T> {
733 fn bitxor(self, other: O) -> Self::Output {
734 self.symmetrical_difference(other.into())
738 impl<T: EnumSetType, O: Into<EnumSet<T>>> SubAssign<O> for EnumSet<T> {
740 fn sub_assign(&mut self, rhs: O) {
744 impl<T: EnumSetType, O: Into<EnumSet<T>>> BitAndAssign<O> for EnumSet<T> {
746 fn bitand_assign(&mut self, rhs: O) {
750 impl<T: EnumSetType, O: Into<EnumSet<T>>> BitOrAssign<O> for EnumSet<T> {
752 fn bitor_assign(&mut self, rhs: O) {
756 impl<T: EnumSetType, O: Into<EnumSet<T>>> BitXorAssign<O> for EnumSet<T> {
758 fn bitxor_assign(&mut self, rhs: O) {
763 impl<T: EnumSetType> Not for EnumSet<T> {
766 fn not(self) -> Self::Output {
771 impl<T: EnumSetType> From<T> for EnumSet<T> {
772 fn from(t: T) -> Self {
777 impl<T: EnumSetType> PartialEq<T> for EnumSet<T> {
778 fn eq(&self, other: &T) -> bool {
779 self.__priv_repr == EnumSet::only(*other).__priv_repr
782 impl<T: EnumSetType + Debug> Debug for EnumSet<T> {
783 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
784 let mut is_first = true;
785 f.write_str("EnumSet(")?;
786 for v in self.iter() {
798 #[allow(clippy::derive_hash_xor_eq)] // This impl exists to change trait bounds only.
799 impl<T: EnumSetType> Hash for EnumSet<T> {
800 fn hash<H: Hasher>(&self, state: &mut H) {
801 self.__priv_repr.hash(state)
804 impl<T: EnumSetType> PartialOrd for EnumSet<T> {
805 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
806 self.__priv_repr.partial_cmp(&other.__priv_repr)
809 impl<T: EnumSetType> Ord for EnumSet<T> {
810 fn cmp(&self, other: &Self) -> Ordering {
811 self.__priv_repr.cmp(&other.__priv_repr)
815 #[cfg(feature = "serde")]
816 impl<T: EnumSetType> Serialize for EnumSet<T> {
817 fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
818 T::serialize(*self, serializer)
822 #[cfg(feature = "serde")]
823 impl<'de, T: EnumSetType> Deserialize<'de> for EnumSet<T> {
824 fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
825 T::deserialize(deserializer)
829 /// The iterator used by [`EnumSet`]s.
830 #[derive(Clone, Debug)]
831 pub struct EnumSetIter<T: EnumSetType> {
834 impl<T: EnumSetType> EnumSetIter<T> {
835 fn new(set: EnumSet<T>) -> EnumSetIter<T> {
840 impl<T: EnumSetType> Iterator for EnumSetIter<T> {
843 fn next(&mut self) -> Option<Self::Item> {
844 if self.set.is_empty() {
847 let bit = self.set.__priv_repr.trailing_zeros();
848 self.set.__priv_repr.remove_bit(bit);
849 unsafe { Some(T::enum_from_u32(bit)) }
852 fn size_hint(&self) -> (usize, Option<usize>) {
853 let left = self.set.len();
858 impl<T: EnumSetType> DoubleEndedIterator for EnumSetIter<T> {
859 fn next_back(&mut self) -> Option<Self::Item> {
860 if self.set.is_empty() {
863 let bit = T::Repr::WIDTH - 1 - self.set.__priv_repr.leading_zeros();
864 self.set.__priv_repr.remove_bit(bit);
865 unsafe { Some(T::enum_from_u32(bit)) }
870 impl<T: EnumSetType> ExactSizeIterator for EnumSetIter<T> {}
872 impl<T: EnumSetType> Extend<T> for EnumSet<T> {
873 fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I) {
874 iter.into_iter().for_each(|v| {
880 impl<T: EnumSetType> FromIterator<T> for EnumSet<T> {
881 fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self {
882 let mut set = EnumSet::default();
888 impl<T: EnumSetType> Extend<EnumSet<T>> for EnumSet<T> {
889 fn extend<I: IntoIterator<Item = EnumSet<T>>>(&mut self, iter: I) {
890 iter.into_iter().for_each(|v| {
896 impl<T: EnumSetType> FromIterator<EnumSet<T>> for EnumSet<T> {
897 fn from_iter<I: IntoIterator<Item = EnumSet<T>>>(iter: I) -> Self {
898 let mut set = EnumSet::default();
904 /// Creates a EnumSet literal, which can be used in const contexts.
906 /// The syntax used is `enum_set!(Type::A | Type::B | Type::C)`. Each variant must be of the same
907 /// type, or a error will occur at compile-time.
909 /// This macro accepts trailing `|`s to allow easier use in other macros.
914 /// # use enumset::*;
915 /// # #[derive(EnumSetType, Debug)] enum Enum { A, B, C }
916 /// const CONST_SET: EnumSet<Enum> = enum_set!(Enum::A | Enum::B);
917 /// assert_eq!(CONST_SET, Enum::A | Enum::B);
920 /// This macro is strongly typed. For example, the following will not compile:
923 /// # use enumset::*;
924 /// # #[derive(EnumSetType, Debug)] enum Enum { A, B, C }
925 /// # #[derive(EnumSetType, Debug)] enum Enum2 { A, B, C }
926 /// let type_error = enum_set!(Enum::A | Enum2::B);
929 macro_rules! enum_set {
931 $crate::EnumSet { __priv_repr: 0 }
933 ($value:path $(|)*) => {
935 #[allow(deprecated)] let value = $value.__impl_enumset_internal__const_only();
939 ($value:path | $($rest:path)|* $(|)*) => {
941 #[allow(deprecated)] let value = $value.__impl_enumset_internal__const_only();
942 $(#[allow(deprecated)] let value = $rest.__impl_enumset_internal__const_merge(value);)*