2 #![forbid(missing_docs)]
4 //! A library for defining enums that can be used in compact bit sets. It supports enums up to 128
5 //! variants, and has a macro to use these sets in constants.
7 //! For serde support, enable the `serde` feature.
9 //! # Defining enums for use with EnumSet
11 //! Enums to be used with [`EnumSet`] should be defined using `#[derive(EnumSetType)]`:
15 //! #[derive(EnumSetType, Debug)]
17 //! A, B, C, D, E, F, G,
21 //! # Working with EnumSets
23 //! EnumSets can be constructed via [`EnumSet::new()`] like a normal set. In addition,
24 //! `#[derive(EnumSetType)]` creates operator overloads that allow you to create EnumSets like so:
28 //! # #[derive(EnumSetType, Debug)] pub enum Enum { A, B, C, D, E, F, G }
29 //! let new_set = Enum::A | Enum::C | Enum::G;
30 //! assert_eq!(new_set.len(), 3);
33 //! All bitwise operations you would expect to work on bitsets also work on both EnumSets and
34 //! enums with `#[derive(EnumSetType)]`:
37 //! # #[derive(EnumSetType, Debug)] pub enum Enum { A, B, C, D, E, F, G }
38 //! // Intersection of sets
39 //! assert_eq!((Enum::A | Enum::B) & Enum::C, EnumSet::empty());
40 //! assert_eq!((Enum::A | Enum::B) & Enum::A, Enum::A);
41 //! assert_eq!(Enum::A & Enum::B, EnumSet::empty());
43 //! // Symmetric difference of sets
44 //! assert_eq!((Enum::A | Enum::B) ^ (Enum::B | Enum::C), Enum::A | Enum::C);
45 //! assert_eq!(Enum::A ^ Enum::C, Enum::A | Enum::C);
47 //! // Difference of sets
48 //! assert_eq!((Enum::A | Enum::B | Enum::C) - Enum::B, Enum::A | Enum::C);
50 //! // Complement of sets
51 //! assert_eq!(!(Enum::E | Enum::G), Enum::A | Enum::B | Enum::C | Enum::D | Enum::F);
54 //! The [`enum_set!`] macro allows you to create EnumSets in constant contexts:
58 //! # #[derive(EnumSetType, Debug)] pub enum Enum { A, B, C, D, E, F, G }
59 //! const CONST_SET: EnumSet<Enum> = enum_set!(Enum::A | Enum::B);
60 //! assert_eq!(CONST_SET, Enum::A | Enum::B);
63 //! Mutable operations on the [`EnumSet`] otherwise work basically as expected:
67 //! # #[derive(EnumSetType, Debug)] pub enum Enum { A, B, C, D, E, F, G }
68 //! let mut set = EnumSet::new();
69 //! set.insert(Enum::A);
70 //! set.insert_all(Enum::E | Enum::G);
71 //! assert!(set.contains(Enum::A));
72 //! assert!(!set.contains(Enum::B));
73 //! assert_eq!(set, Enum::A | Enum::E | Enum::G);
76 pub use enumset_derive::*;
78 use core::cmp::Ordering;
80 use core::fmt::{Debug, Formatter};
81 use core::hash::{Hash, Hasher};
82 use core::iter::FromIterator;
88 /// Everything in this module is internal API and may change at any time.
92 /// A struct used to type check [`enum_set!`].
93 pub struct EnumSetSameTypeHack<'a, T: EnumSetType + 'static> {
95 pub enum_set: EnumSet<T>,
98 /// A reexport of core to allow our macros to be generic to std vs core.
99 pub use ::core as core_export;
101 /// A reexport of serde so there is no requirement to depend on serde.
102 #[cfg(feature = "serde")] pub use serde2 as serde;
104 /// The actual members of EnumSetType. Put here to avoid polluting global namespaces.
105 pub unsafe trait EnumSetTypePrivate {
106 type Repr: EnumSetTypeRepr;
107 const ALL_BITS: Self::Repr;
108 fn enum_into_u32(self) -> u32;
109 unsafe fn enum_from_u32(val: u32) -> Self;
111 #[cfg(feature = "serde")]
112 fn serialize<S: serde::Serializer>(set: EnumSet<Self>, ser: S) -> Result<S::Ok, S::Error>
113 where Self: EnumSetType;
114 #[cfg(feature = "serde")]
115 fn deserialize<'de, D: serde::Deserializer<'de>>(de: D) -> Result<EnumSet<Self>, D::Error>
116 where Self: EnumSetType;
119 use crate::internal::EnumSetTypePrivate;
120 #[cfg(feature = "serde")] use crate::internal::serde;
121 #[cfg(feature = "serde")] use crate::serde::{Serialize, Deserialize};
126 pub trait EnumSetTypeRepr :
127 PrimInt + WrappingSub + CheckedShl + Debug + Hash + FromPrimitive + ToPrimitive +
128 AsPrimitive<u8> + AsPrimitive<u16> + AsPrimitive<u32> + AsPrimitive<u64> +
129 AsPrimitive<u128> + AsPrimitive<usize>
133 fn from_u8(v: u8) -> Self;
134 fn from_u16(v: u16) -> Self;
135 fn from_u32(v: u32) -> Self;
136 fn from_u64(v: u64) -> Self;
137 fn from_u128(v: u128) -> Self;
138 fn from_usize(v: usize) -> Self;
141 ($name:ty, $width:expr) => {
142 impl EnumSetTypeRepr for $name {
143 const WIDTH: u32 = $width;
144 fn from_u8(v: u8) -> Self { v.as_() }
145 fn from_u16(v: u16) -> Self { v.as_() }
146 fn from_u32(v: u32) -> Self { v.as_() }
147 fn from_u64(v: u64) -> Self { v.as_() }
148 fn from_u128(v: u128) -> Self { v.as_() }
149 fn from_usize(v: usize) -> Self { v.as_() }
159 use crate::private::EnumSetTypeRepr;
161 /// The trait used to define enum types that may be used with [`EnumSet`].
163 /// This trait should be implemented using `#[derive(EnumSetType)]`. Its internal structure is
164 /// not currently stable, and may change at any time.
168 /// The custom derive for [`EnumSetType`] automatically creates implementations of [`PartialEq`],
169 /// [`Sub`], [`BitAnd`], [`BitOr`], [`BitXor`], and [`Not`] allowing the enum to be used as
170 /// if it were an [`EnumSet`] in expressions. This can be disabled by adding an `#[enumset(no_ops)]`
171 /// annotation to the enum.
173 /// The custom derive for `EnumSetType` automatically implements [`Copy`], [`Clone`], [`Eq`], and
174 /// [`PartialEq`] on the enum. These are required for the [`EnumSet`] to function.
176 /// Any C-like enum is supported, as long as there are no more than 128 variants in the enum,
177 /// and no variant discriminator is larger than 127.
181 /// Deriving a plain EnumSetType:
184 /// # use enumset::*;
185 /// #[derive(EnumSetType)]
187 /// A, B, C, D, E, F, G,
191 /// Deriving a sparse EnumSetType:
194 /// # use enumset::*;
195 /// #[derive(EnumSetType)]
196 /// pub enum SparseEnum {
197 /// A = 10, B = 20, C = 30, D = 127,
201 /// Deriving an EnumSetType without adding ops:
204 /// # use enumset::*;
205 /// #[derive(EnumSetType)]
206 /// #[enumset(no_ops)]
207 /// pub enum NoOpsEnum {
208 /// A, B, C, D, E, F, G,
211 pub unsafe trait EnumSetType: Copy + Eq + EnumSetTypePrivate { }
213 /// An efficient set type for enums.
215 /// It is implemented using a bitset stored using the smallest integer that can fit all bits
216 /// in the underlying enum.
220 /// By default, `EnumSet`s are serialized as an unsigned integer of the same width as used to store
223 /// Unknown bits are ignored, and are simply dropped. To override this behavior, you can add a
224 /// `#[enumset(serialize_deny_unknown)]` annotation to your enum.
226 /// You can add a `#[enumset(serialize_repr = "u8")]` annotation to your enum to manually set
227 /// the number width the `EnumSet` is serialized as. Only unsigned integer types may be used. This
228 /// can be used to avoid breaking changes in certain serialization formats (such as `bincode`).
230 /// In addition, the `#[enumset(serialize_as_list)]` annotation causes the `EnumSet` to be
231 /// instead serialized as a list of enum variants. This requires your enum type implement
232 /// [`Serialize`] and [`Deserialize`].
233 #[derive(Copy, Clone, PartialEq, Eq)]
234 pub struct EnumSet<T: EnumSetType> {
236 /// This is public due to the [`enum_set!`] macro.
237 /// This is **NOT** public API and may change at any time.
238 pub __enumset_underlying: T::Repr
240 impl <T: EnumSetType> EnumSet<T> {
241 fn mask(bit: u32) -> T::Repr {
242 Shl::<usize>::shl(T::Repr::one(), bit as usize)
244 fn has_bit(&self, bit: u32) -> bool {
245 let mask = Self::mask(bit);
246 self.__enumset_underlying & mask == mask
248 fn partial_bits(bits: u32) -> T::Repr {
249 T::Repr::one().checked_shl(bits as u32)
250 .unwrap_or(T::Repr::zero())
251 .wrapping_sub(&T::Repr::one())
254 // Returns all bits valid for the enum
255 fn all_bits() -> T::Repr {
259 /// Creates an empty `EnumSet`.
260 pub fn new() -> Self {
261 EnumSet { __enumset_underlying: T::Repr::zero() }
264 /// Returns an `EnumSet` containing a single element.
265 pub fn only(t: T) -> Self {
266 EnumSet { __enumset_underlying: Self::mask(t.enum_into_u32()) }
269 /// Creates an empty `EnumSet`.
271 /// This is an alias for [`EnumSet::new`].
272 pub fn empty() -> Self {
276 /// Returns an `EnumSet` containing all valid variants of the enum.
277 pub fn all() -> Self {
278 EnumSet { __enumset_underlying: Self::all_bits() }
281 /// Total number of bits used by this type. Note that the actual amount of space used is
282 /// rounded up to the next highest integer type (`u8`, `u16`, `u32`, `u64`, or `u128`).
284 /// This is the same as [`EnumSet::variant_count`] except in enums with "sparse" variants.
285 /// (e.g. `enum Foo { A = 10, B = 20 }`)
286 pub fn bit_width() -> u32 {
287 T::Repr::WIDTH - T::ALL_BITS.leading_zeros()
290 /// The number of valid variants that this type can contain.
292 /// This is the same as [`EnumSet::bit_width`] except in enums with "sparse" variants.
293 /// (e.g. `enum Foo { A = 10, B = 20 }`)
294 pub fn variant_count() -> u32 {
295 T::ALL_BITS.count_ones()
298 /// Returns the number of elements in this set.
299 pub fn len(&self) -> usize {
300 self.__enumset_underlying.count_ones() as usize
302 /// Returns `true` if the set contains no elements.
303 pub fn is_empty(&self) -> bool {
304 self.__enumset_underlying.is_zero()
306 /// Removes all elements from the set.
307 pub fn clear(&mut self) {
308 self.__enumset_underlying = T::Repr::zero()
311 /// Returns `true` if `self` has no elements in common with `other`. This is equivalent to
312 /// checking for an empty intersection.
313 pub fn is_disjoint(&self, other: Self) -> bool {
314 (*self & other).is_empty()
316 /// Returns `true` if the set is a superset of another, i.e., `self` contains at least all the
317 /// values in `other`.
318 pub fn is_superset(&self, other: Self) -> bool {
319 (*self & other).__enumset_underlying == other.__enumset_underlying
321 /// Returns `true` if the set is a subset of another, i.e., `other` contains at least all
322 /// the values in `self`.
323 pub fn is_subset(&self, other: Self) -> bool {
324 other.is_superset(*self)
327 /// Returns a set containing any elements present in either set.
328 pub fn union(&self, other: Self) -> Self {
329 EnumSet { __enumset_underlying: self.__enumset_underlying | other.__enumset_underlying }
331 /// Returns a set containing every element present in both sets.
332 pub fn intersection(&self, other: Self) -> Self {
333 EnumSet { __enumset_underlying: self.__enumset_underlying & other.__enumset_underlying }
335 /// Returns a set containing element present in `self` but not in `other`.
336 pub fn difference(&self, other: Self) -> Self {
337 EnumSet { __enumset_underlying: self.__enumset_underlying & !other.__enumset_underlying }
339 /// Returns a set containing every element present in either `self` or `other`, but is not
341 pub fn symmetrical_difference(&self, other: Self) -> Self {
342 EnumSet { __enumset_underlying: self.__enumset_underlying ^ other.__enumset_underlying }
344 /// Returns a set containing all enum variants not in this set.
345 pub fn complement(&self) -> Self {
346 EnumSet { __enumset_underlying: !self.__enumset_underlying & Self::all_bits() }
349 /// Checks whether this set contains a value.
350 pub fn contains(&self, value: T) -> bool {
351 self.has_bit(value.enum_into_u32())
354 /// Adds a value to this set.
356 /// If the set did not have this value present, `true` is returned.
358 /// If the set did have this value present, `false` is returned.
359 pub fn insert(&mut self, value: T) -> bool {
360 let contains = !self.contains(value);
361 self.__enumset_underlying = self.__enumset_underlying | Self::mask(value.enum_into_u32());
364 /// Removes a value from this set. Returns whether the value was present in the set.
365 pub fn remove(&mut self, value: T) -> bool {
366 let contains = self.contains(value);
367 self.__enumset_underlying = self.__enumset_underlying & !Self::mask(value.enum_into_u32());
371 /// Adds all elements in another set to this one.
372 pub fn insert_all(&mut self, other: Self) {
373 self.__enumset_underlying = self.__enumset_underlying | other.__enumset_underlying
375 /// Removes all values in another set from this one.
376 pub fn remove_all(&mut self, other: Self) {
377 self.__enumset_underlying = self.__enumset_underlying & !other.__enumset_underlying
380 /// Creates an iterator over the values in this set.
382 /// Note that iterator invalidation is impossible as the iterator contains a copy of this type,
383 /// rather than holding a reference to it.
384 pub fn iter(&self) -> EnumSetIter<T> {
385 EnumSetIter(*self, 0)
389 macro_rules! conversion_impls {
392 $underlying:ty, $underlying_str:expr, $from_fn:ident, $to_fn:ident,
393 $from:ident $try_from:ident $from_truncated:ident
394 $to:ident $try_to:ident $to_truncated:ident
397 impl <T : EnumSetType> EnumSet<T> {$(
398 #[doc = "Returns a `"]
399 #[doc = $underlying_str]
400 #[doc = "` representing the elements of this set. \n\nIf the underlying bitset will \
402 #[doc = $underlying_str]
403 #[doc = "`, this method will panic."]
404 pub fn $to(&self) -> $underlying {
405 self.$try_to().expect("Bitset will not fit into this type.")
408 #[doc = "Tries to return a `"]
409 #[doc = $underlying_str]
410 #[doc = "` representing the elements of this set. \n\nIf the underlying bitset will \
412 #[doc = $underlying_str]
413 #[doc = "`, this method will instead return `None`."]
414 pub fn $try_to(&self) -> Option<$underlying> {
415 self.__enumset_underlying.$to_fn()
418 #[doc = "Returns a truncated `"]
419 #[doc = $underlying_str]
420 #[doc = "` representing the elements of this set. \n\nIf the underlying bitset will \
422 #[doc = $underlying_str]
423 #[doc = "`, this method will truncate any bits that don't fit."]
424 pub fn $to_truncated(&self) -> $underlying {
425 AsPrimitive::<$underlying>::as_(self.__enumset_underlying)
428 #[doc = "Constructs a bitset from a `"]
429 #[doc = $underlying_str]
430 #[doc = "`. \n\nIf a bit that doesn't correspond to an enum variant is set, this \
432 pub fn $from(bits: $underlying) -> Self {
433 Self::$try_from(bits).expect("Bitset contains invalid variants.")
436 #[doc = "Attempts to constructs a bitset from a `"]
437 #[doc = $underlying_str]
438 #[doc = "`. \n\nIf a bit that doesn't correspond to an enum variant is set, this \
439 method will return `None`."]
440 pub fn $try_from(bits: $underlying) -> Option<Self> {
441 let bits = <T::Repr as FromPrimitive>::$from_fn(bits);
442 let mask = Self::all().__enumset_underlying;
443 bits.and_then(|bits| if (bits & !mask) == T::Repr::zero() {
444 Some(EnumSet { __enumset_underlying: bits })
450 #[doc = "Constructs a bitset from a `"]
451 #[doc = $underlying_str]
452 #[doc = "`, ignoring invalid variants."]
453 pub fn $from_truncated(bits: $underlying) -> Self {
454 let mask = Self::all().$to_truncated();
455 let bits = <T::Repr as EnumSetTypeRepr>::$from_fn(bits & mask);
456 EnumSet { __enumset_underlying: bits }
463 for_num!(u8, "u8", from_u8, to_u8,
464 from_u8 try_from_u8 from_u8_truncated as_u8 try_as_u8 as_u8_truncated);
465 for_num!(u16, "u16", from_u16, to_u16,
466 from_u16 try_from_u16 from_u16_truncated as_u16 try_as_u16 as_u16_truncated);
467 for_num!(u32, "u32", from_u32, to_u32,
468 from_u32 try_from_u32 from_u32_truncated as_u32 try_as_u32 as_u32_truncated);
469 for_num!(u64, "u64", from_u64, to_u64,
470 from_u64 try_from_u64 from_u64_truncated as_u64 try_as_u64 as_u64_truncated);
471 for_num!(u128, "u128", from_u128, to_u128,
472 from_u128 try_from_u128 from_u128_truncated as_u128 try_as_u128 as_u128_truncated);
473 for_num!(usize, "usize", from_usize, to_usize,
474 from_usize try_from_usize from_usize_truncated
475 as_usize try_as_usize as_usize_truncated);
478 impl <T: EnumSetType> Default for EnumSet<T> {
479 /// Returns an empty set.
480 fn default() -> Self {
485 impl <T: EnumSetType> IntoIterator for EnumSet<T> {
487 type IntoIter = EnumSetIter<T>;
489 fn into_iter(self) -> Self::IntoIter {
494 impl <T: EnumSetType, O: Into<EnumSet<T>>> Sub<O> for EnumSet<T> {
496 fn sub(self, other: O) -> Self::Output {
497 self.difference(other.into())
500 impl <T: EnumSetType, O: Into<EnumSet<T>>> BitAnd<O> for EnumSet<T> {
502 fn bitand(self, other: O) -> Self::Output {
503 self.intersection(other.into())
506 impl <T: EnumSetType, O: Into<EnumSet<T>>> BitOr<O> for EnumSet<T> {
508 fn bitor(self, other: O) -> Self::Output {
509 self.union(other.into())
512 impl <T: EnumSetType, O: Into<EnumSet<T>>> BitXor<O> for EnumSet<T> {
514 fn bitxor(self, other: O) -> Self::Output {
515 self.symmetrical_difference(other.into())
519 impl <T: EnumSetType, O: Into<EnumSet<T>>> SubAssign<O> for EnumSet<T> {
520 fn sub_assign(&mut self, rhs: O) {
524 impl <T: EnumSetType, O: Into<EnumSet<T>>> BitAndAssign<O> for EnumSet<T> {
525 fn bitand_assign(&mut self, rhs: O) {
529 impl <T: EnumSetType, O: Into<EnumSet<T>>> BitOrAssign<O> for EnumSet<T> {
530 fn bitor_assign(&mut self, rhs: O) {
534 impl <T: EnumSetType, O: Into<EnumSet<T>>> BitXorAssign<O> for EnumSet<T> {
535 fn bitxor_assign(&mut self, rhs: O) {
540 impl <T: EnumSetType> Not for EnumSet<T> {
542 fn not(self) -> Self::Output {
547 impl <T: EnumSetType> From<T> for EnumSet<T> {
548 fn from(t: T) -> Self {
553 impl <T: EnumSetType> PartialEq<T> for EnumSet<T> {
554 fn eq(&self, other: &T) -> bool {
555 self.__enumset_underlying == EnumSet::<T>::mask(other.enum_into_u32())
558 impl <T: EnumSetType + Debug> Debug for EnumSet<T> {
559 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
560 let mut is_first = true;
561 f.write_str("EnumSet(")?;
562 for v in self.iter() {
563 if !is_first { f.write_str(" | ")?; }
572 impl <T: EnumSetType> Hash for EnumSet<T> {
573 fn hash<H: Hasher>(&self, state: &mut H) {
574 self.__enumset_underlying.hash(state)
577 impl <T: EnumSetType> PartialOrd for EnumSet<T> {
578 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
579 self.__enumset_underlying.partial_cmp(&other.__enumset_underlying)
582 impl <T: EnumSetType> Ord for EnumSet<T> {
583 fn cmp(&self, other: &Self) -> Ordering {
584 self.__enumset_underlying.cmp(&other.__enumset_underlying)
588 #[cfg(feature = "serde")]
589 impl <T: EnumSetType> Serialize for EnumSet<T> {
590 fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
591 T::serialize(*self, serializer)
595 #[cfg(feature = "serde")]
596 impl <'de, T: EnumSetType> Deserialize<'de> for EnumSet<T> {
597 fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
598 T::deserialize(deserializer)
602 /// The iterator used by [`EnumSet`]s.
603 #[derive(Clone, Debug)]
604 pub struct EnumSetIter<T: EnumSetType>(EnumSet<T>, u32);
605 impl <T: EnumSetType> Iterator for EnumSetIter<T> {
608 fn next(&mut self) -> Option<Self::Item> {
609 while self.1 < EnumSet::<T>::bit_width() {
612 if self.0.has_bit(bit) {
613 return unsafe { Some(T::enum_from_u32(bit)) }
618 fn size_hint(&self) -> (usize, Option<usize>) {
619 let left_mask = !EnumSet::<T>::partial_bits(self.1);
620 let left = (self.0.__enumset_underlying & left_mask).count_ones() as usize;
625 impl<T: EnumSetType> Extend<T> for EnumSet<T> {
626 fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I) {
627 iter.into_iter().for_each(|v| { self.insert(v); });
631 impl<T: EnumSetType> FromIterator<T> for EnumSet<T> {
632 fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self {
633 let mut set = EnumSet::default();
639 /// Creates a EnumSet literal, which can be used in const contexts.
641 /// The syntax used is `enum_set!(Type::A | Type::B | Type::C)`. Each variant must be of the same
642 /// type, or a error will occur at compile-time.
647 /// # use enumset::*;
648 /// # #[derive(EnumSetType, Debug)] enum Enum { A, B, C }
649 /// const CONST_SET: EnumSet<Enum> = enum_set!(Enum::A | Enum::B);
650 /// assert_eq!(CONST_SET, Enum::A | Enum::B);
653 /// This macro is strongly typed. For example, the following will not compile:
656 /// # use enumset::*;
657 /// # #[derive(EnumSetType, Debug)] enum Enum { A, B, C }
658 /// # #[derive(EnumSetType, Debug)] enum Enum2 { A, B, C }
659 /// let type_error = enum_set!(Enum::A | Enum2::B);
662 macro_rules! enum_set {
664 $crate::EnumSet { __enumset_underlying: 0 }
666 ($($value:path)|* $(|)*) => {
667 $crate::internal::EnumSetSameTypeHack {
668 unified: &[$($value,)*],
669 enum_set: $crate::EnumSet {
670 __enumset_underlying: 0 $(| (1 << ($value as u32)))*