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 //! For more information on more advanced use cases, see the documentation for [`EnumSetType`].
23 //! # Working with EnumSets
25 //! EnumSets can be constructed via [`EnumSet::new()`] like a normal set. In addition,
26 //! `#[derive(EnumSetType)]` creates operator overloads that allow you to create EnumSets like so:
30 //! # #[derive(EnumSetType, Debug)] pub enum Enum { A, B, C, D, E, F, G }
31 //! let new_set = Enum::A | Enum::C | Enum::G;
32 //! assert_eq!(new_set.len(), 3);
35 //! All bitwise operations you would expect to work on bitsets also work on both EnumSets and
36 //! enums with `#[derive(EnumSetType)]`:
39 //! # #[derive(EnumSetType, Debug)] pub enum Enum { A, B, C, D, E, F, G }
40 //! // Intersection of sets
41 //! assert_eq!((Enum::A | Enum::B) & Enum::C, EnumSet::empty());
42 //! assert_eq!((Enum::A | Enum::B) & Enum::A, Enum::A);
43 //! assert_eq!(Enum::A & Enum::B, EnumSet::empty());
45 //! // Symmetric difference of sets
46 //! assert_eq!((Enum::A | Enum::B) ^ (Enum::B | Enum::C), Enum::A | Enum::C);
47 //! assert_eq!(Enum::A ^ Enum::C, Enum::A | Enum::C);
49 //! // Difference of sets
50 //! assert_eq!((Enum::A | Enum::B | Enum::C) - Enum::B, Enum::A | Enum::C);
52 //! // Complement of sets
53 //! assert_eq!(!(Enum::E | Enum::G), Enum::A | Enum::B | Enum::C | Enum::D | Enum::F);
56 //! The [`enum_set!`] macro allows you to create EnumSets in constant contexts:
60 //! # #[derive(EnumSetType, Debug)] pub enum Enum { A, B, C, D, E, F, G }
61 //! const CONST_SET: EnumSet<Enum> = enum_set!(Enum::A | Enum::B);
62 //! assert_eq!(CONST_SET, Enum::A | Enum::B);
65 //! Mutable operations on the [`EnumSet`] otherwise similarly to Rust's builtin sets:
69 //! # #[derive(EnumSetType, Debug)] pub enum Enum { A, B, C, D, E, F, G }
70 //! let mut set = EnumSet::new();
71 //! set.insert(Enum::A);
72 //! set.insert_all(Enum::E | Enum::G);
73 //! assert!(set.contains(Enum::A));
74 //! assert!(!set.contains(Enum::B));
75 //! assert_eq!(set, Enum::A | Enum::E | Enum::G);
78 pub use enumset_derive::EnumSetType;
80 use core::cmp::Ordering;
82 use core::fmt::{Debug, Formatter};
83 use core::hash::{Hash, Hasher};
84 use core::iter::FromIterator;
88 /// Everything in this module is internal API and may change at any time.
92 /// A reexport of core to allow our macros to be generic to std vs core.
93 pub use ::core as core_export;
95 /// A reexport of serde so there is no requirement to depend on serde.
96 #[cfg(feature = "serde")] pub use serde2 as serde;
98 /// The actual members of EnumSetType. Put here to avoid polluting global namespaces.
99 pub unsafe trait EnumSetTypePrivate {
100 /// The underlying type used to store the bitset.
101 type Repr: EnumSetTypeRepr;
102 /// A mask of bits that are valid in the bitset.
103 const ALL_BITS: Self::Repr;
105 /// Converts an enum of this type into its bit position.
106 fn enum_into_u32(self) -> u32;
107 /// Converts a bit position into an enum value.
108 unsafe fn enum_from_u32(val: u32) -> Self;
110 /// Serializes the `EnumSet`.
112 /// This and `deserialize` are part of the `EnumSetType` trait so the procedural derive
113 /// can control how `EnumSet` is serialized.
114 #[cfg(feature = "serde")]
115 fn serialize<S: serde::Serializer>(set: EnumSet<Self>, ser: S) -> Result<S::Ok, S::Error>
116 where Self: EnumSetType;
117 /// Deserializes the `EnumSet`.
118 #[cfg(feature = "serde")]
119 fn deserialize<'de, D: serde::Deserializer<'de>>(de: D) -> Result<EnumSet<Self>, D::Error>
120 where Self: EnumSetType;
123 use crate::__internal::EnumSetTypePrivate;
124 #[cfg(feature = "serde")] use crate::__internal::serde;
125 #[cfg(feature = "serde")] use crate::serde::{Serialize, Deserialize};
128 use crate::repr::EnumSetTypeRepr;
130 /// The trait used to define enum types that may be used with [`EnumSet`].
132 /// This trait should be implemented using `#[derive(EnumSetType)]`. Its internal structure is
133 /// not stable, and may change at any time.
137 /// Any C-like enum is supported, as long as there are no more than 128 variants in the enum,
138 /// and no variant discriminator is larger than 127.
140 /// The custom derive for [`EnumSetType`] automatically creates implementations of [`PartialEq`],
141 /// [`Sub`], [`BitAnd`], [`BitOr`], [`BitXor`], and [`Not`] allowing the enum to be used as
142 /// if it were an [`EnumSet`] in expressions. This can be disabled by adding an `#[enumset(no_ops)]`
143 /// annotation to the enum.
145 /// The custom derive for `EnumSetType` automatically implements [`Copy`], [`Clone`], [`Eq`], and
146 /// [`PartialEq`] on the enum. These are required for the [`EnumSet`] to function.
148 /// In addition, if you have renamed the `enumset` crate in your crate, you can use the
149 /// `#[enumset(crate_name = "enumset2")]` attribute to tell the custom derive to use that name
152 /// Attributes controlling the serialization of an `EnumSet` are documented in
153 /// [its documentation](./struct.EnumSet.html#serialization).
157 /// Deriving a plain EnumSetType:
160 /// # use enumset::*;
161 /// #[derive(EnumSetType)]
163 /// A, B, C, D, E, F, G,
167 /// Deriving a sparse EnumSetType:
170 /// # use enumset::*;
171 /// #[derive(EnumSetType)]
172 /// pub enum SparseEnum {
173 /// A = 10, B = 20, C = 30, D = 127,
177 /// Deriving an EnumSetType without adding ops:
180 /// # use enumset::*;
181 /// #[derive(EnumSetType)]
182 /// #[enumset(no_ops)]
183 /// pub enum NoOpsEnum {
184 /// A, B, C, D, E, F, G,
187 pub unsafe trait EnumSetType: Copy + Eq + EnumSetTypePrivate { }
189 /// An efficient set type for enums.
191 /// It is implemented using a bitset stored using the smallest integer that can fit all bits
192 /// in the underlying enum. In general, an enum variant with a numeric value of `n` is stored in
193 /// the nth least significant bit (corresponding with a mask of, e.g. `1 << enum as u32`).
197 /// When the `serde` feature is enabled, `EnumSet`s can be serialized and deserialized using
198 /// the `serde` crate. The exact serialization format can be controlled with additional attributes
199 /// on the enum type. These attributes are valid regardless of whether the `serde` feature
202 /// By default, `EnumSet`s serialize by directly writing out the underlying bitset as an integer
203 /// of the smallest type that can fit in the underlying enum. You can add a
204 /// `#[enumset(serialize_repr = "u8")]` attribute to your enum to control the integer type used
205 /// for serialization. This can be important for avoiding unintentional breaking changes when
206 /// `EnumSet`s are serialized with formats like `bincode`.
208 /// By default, unknown bits are ignored and silently removed from the bitset. To override this
209 /// behavior, you can add a `#[enumset(serialize_deny_unknown)]` attribute. This will cause
210 /// deserialization to fail if an invalid bit is set.
212 /// In addition, the `#[enumset(serialize_as_list)]` attribute causes the `EnumSet` to be
213 /// instead serialized as a list of enum variants. This requires your enum type implement
214 /// [`Serialize`] and [`Deserialize`]. Note that this is a breaking change
215 #[derive(Copy, Clone, PartialEq, Eq)]
216 pub struct EnumSet<T: EnumSetType> {
218 /// This is public due to the [`enum_set!`] macro.
219 /// This is **NOT** public API and may change at any time.
220 pub __priv_repr: T::Repr
222 impl <T: EnumSetType> EnumSet<T> {
223 // Returns all bits valid for the enum
224 fn all_bits() -> T::Repr {
228 /// Creates an empty `EnumSet`.
229 pub fn new() -> Self {
230 EnumSet { __priv_repr: T::Repr::empty() }
233 /// Returns an `EnumSet` containing a single element.
234 pub fn only(t: T) -> Self {
235 let mut set = Self::new();
240 /// Creates an empty `EnumSet`.
242 /// This is an alias for [`EnumSet::new`].
243 pub fn empty() -> Self {
247 /// Returns an `EnumSet` containing all valid variants of the enum.
248 pub fn all() -> Self {
249 EnumSet { __priv_repr: Self::all_bits() }
252 /// Total number of bits used by this type. Note that the actual amount of space used is
253 /// rounded up to the next highest integer type (`u8`, `u16`, `u32`, `u64`, or `u128`).
255 /// This is the same as [`EnumSet::variant_count`] except in enums with "sparse" variants.
256 /// (e.g. `enum Foo { A = 10, B = 20 }`)
257 pub fn bit_width() -> u32 {
258 T::Repr::WIDTH - T::ALL_BITS.leading_zeros()
261 /// The number of valid variants that this type can contain.
263 /// This is the same as [`EnumSet::bit_width`] except in enums with "sparse" variants.
264 /// (e.g. `enum Foo { A = 10, B = 20 }`)
265 pub fn variant_count() -> u32 {
266 T::ALL_BITS.count_ones()
269 /// Returns the number of elements in this set.
270 pub fn len(&self) -> usize {
271 self.__priv_repr.count_ones() as usize
273 /// Returns `true` if the set contains no elements.
274 pub fn is_empty(&self) -> bool {
275 self.__priv_repr.is_empty()
277 /// Removes all elements from the set.
278 pub fn clear(&mut self) {
279 self.__priv_repr = T::Repr::empty()
282 /// Returns `true` if `self` has no elements in common with `other`. This is equivalent to
283 /// checking for an empty intersection.
284 pub fn is_disjoint(&self, other: Self) -> bool {
285 (*self & other).is_empty()
287 /// Returns `true` if the set is a superset of another, i.e., `self` contains at least all the
288 /// values in `other`.
289 pub fn is_superset(&self, other: Self) -> bool {
290 (*self & other).__priv_repr == other.__priv_repr
292 /// Returns `true` if the set is a subset of another, i.e., `other` contains at least all
293 /// the values in `self`.
294 pub fn is_subset(&self, other: Self) -> bool {
295 other.is_superset(*self)
298 /// Returns a set containing any elements present in either set.
299 pub fn union(&self, other: Self) -> Self {
300 EnumSet { __priv_repr: self.__priv_repr | other.__priv_repr }
302 /// Returns a set containing every element present in both sets.
303 pub fn intersection(&self, other: Self) -> Self {
304 EnumSet { __priv_repr: self.__priv_repr & other.__priv_repr }
306 /// Returns a set containing element present in `self` but not in `other`.
307 pub fn difference(&self, other: Self) -> Self {
308 EnumSet { __priv_repr: self.__priv_repr.and_not(other.__priv_repr) }
310 /// Returns a set containing every element present in either `self` or `other`, but is not
312 pub fn symmetrical_difference(&self, other: Self) -> Self {
313 EnumSet { __priv_repr: self.__priv_repr ^ other.__priv_repr }
315 /// Returns a set containing all enum variants not in this set.
316 pub fn complement(&self) -> Self {
317 EnumSet { __priv_repr: !self.__priv_repr & Self::all_bits() }
320 /// Checks whether this set contains a value.
321 pub fn contains(&self, value: T) -> bool {
322 self.__priv_repr.has_bit(value.enum_into_u32())
325 /// Adds a value to this set.
327 /// If the set did not have this value present, `true` is returned.
329 /// If the set did have this value present, `false` is returned.
330 pub fn insert(&mut self, value: T) -> bool {
331 let contains = !self.contains(value);
332 self.__priv_repr.add_bit(value.enum_into_u32());
335 /// Removes a value from this set. Returns whether the value was present in the set.
336 pub fn remove(&mut self, value: T) -> bool {
337 let contains = self.contains(value);
338 self.__priv_repr.remove_bit(value.enum_into_u32());
342 /// Adds all elements in another set to this one.
343 pub fn insert_all(&mut self, other: Self) {
344 self.__priv_repr = self.__priv_repr | other.__priv_repr
346 /// Removes all values in another set from this one.
347 pub fn remove_all(&mut self, other: Self) {
348 self.__priv_repr = self.__priv_repr.and_not(other.__priv_repr);
351 /// Creates an iterator over the values in this set.
353 /// Note that iterator invalidation is impossible as the iterator contains a copy of this type,
354 /// rather than holding a reference to it.
355 pub fn iter(&self) -> EnumSetIter<T> {
356 EnumSetIter(*self, 0)
360 /// Helper macro for generating conversion functions.
361 macro_rules! conversion_impls {
364 $underlying:ty, $underlying_str:expr,
365 $from_fn:ident $to_fn:ident $from_fn_opt:ident $to_fn_opt:ident,
366 $from:ident $try_from:ident $from_truncated:ident
367 $to:ident $try_to:ident $to_truncated:ident
370 impl <T : EnumSetType> EnumSet<T> {$(
371 #[doc = "Returns a `"]
372 #[doc = $underlying_str]
373 #[doc = "` representing the elements of this set.\n\nIf the underlying bitset will \
375 #[doc = $underlying_str]
376 #[doc = "`, this method will panic."]
377 pub fn $to(&self) -> $underlying {
378 self.$try_to().expect("Bitset will not fit into this type.")
381 #[doc = "Tries to return a `"]
382 #[doc = $underlying_str]
383 #[doc = "` representing the elements of this set.\n\nIf the underlying bitset will \
385 #[doc = $underlying_str]
386 #[doc = "`, this method will instead return `None`."]
387 pub fn $try_to(&self) -> Option<$underlying> {
388 EnumSetTypeRepr::$to_fn_opt(&self.__priv_repr)
391 #[doc = "Returns a truncated `"]
392 #[doc = $underlying_str]
393 #[doc = "` representing the elements of this set.\n\nIf the underlying bitset will \
395 #[doc = $underlying_str]
396 #[doc = "`, this method will truncate any bits that don't fit."]
397 pub fn $to_truncated(&self) -> $underlying {
398 EnumSetTypeRepr::$to_fn(&self.__priv_repr)
401 #[doc = "Constructs a bitset from a `"]
402 #[doc = $underlying_str]
403 #[doc = "`.\n\nIf a bit that doesn't correspond to an enum variant is set, this \
405 pub fn $from(bits: $underlying) -> Self {
406 Self::$try_from(bits).expect("Bitset contains invalid variants.")
409 #[doc = "Attempts to constructs a bitset from a `"]
410 #[doc = $underlying_str]
411 #[doc = "`.\n\nIf a bit that doesn't correspond to an enum variant is set, this \
412 method will return `None`."]
413 pub fn $try_from(bits: $underlying) -> Option<Self> {
414 let bits = T::Repr::$from_fn_opt(bits);
415 let mask = Self::all().__priv_repr;
416 bits.and_then(|bits| if bits.and_not(mask).is_empty() {
417 Some(EnumSet { __priv_repr: bits })
423 #[doc = "Constructs a bitset from a `"]
424 #[doc = $underlying_str]
425 #[doc = "`, ignoring invalid variants."]
426 pub fn $from_truncated(bits: $underlying) -> Self {
427 let mask = Self::all().$to_truncated();
428 let bits = <T::Repr as EnumSetTypeRepr>::$from_fn(bits & mask);
429 EnumSet { __priv_repr: bits }
435 for_num!(u8, "u8", from_u8 to_u8 from_u8_opt to_u8_opt,
436 from_u8 try_from_u8 from_u8_truncated as_u8 try_as_u8 as_u8_truncated);
437 for_num!(u16, "u16", from_u16 to_u16 from_u16_opt to_u16_opt,
438 from_u16 try_from_u16 from_u16_truncated as_u16 try_as_u16 as_u16_truncated);
439 for_num!(u32, "u32", from_u32 to_u32 from_u32_opt to_u32_opt,
440 from_u32 try_from_u32 from_u32_truncated as_u32 try_as_u32 as_u32_truncated);
441 for_num!(u64, "u64", from_u64 to_u64 from_u64_opt to_u64_opt,
442 from_u64 try_from_u64 from_u64_truncated as_u64 try_as_u64 as_u64_truncated);
443 for_num!(u128, "u128", from_u128 to_u128 from_u128_opt to_u128_opt,
444 from_u128 try_from_u128 from_u128_truncated as_u128 try_as_u128 as_u128_truncated);
445 for_num!(usize, "usize", from_usize to_usize from_usize_opt to_usize_opt,
446 from_usize try_from_usize from_usize_truncated
447 as_usize try_as_usize as_usize_truncated);
450 impl <T: EnumSetType> Default for EnumSet<T> {
451 /// Returns an empty set.
452 fn default() -> Self {
457 impl <T: EnumSetType> IntoIterator for EnumSet<T> {
459 type IntoIter = EnumSetIter<T>;
461 fn into_iter(self) -> Self::IntoIter {
466 impl <T: EnumSetType, O: Into<EnumSet<T>>> Sub<O> for EnumSet<T> {
468 fn sub(self, other: O) -> Self::Output {
469 self.difference(other.into())
472 impl <T: EnumSetType, O: Into<EnumSet<T>>> BitAnd<O> for EnumSet<T> {
474 fn bitand(self, other: O) -> Self::Output {
475 self.intersection(other.into())
478 impl <T: EnumSetType, O: Into<EnumSet<T>>> BitOr<O> for EnumSet<T> {
480 fn bitor(self, other: O) -> Self::Output {
481 self.union(other.into())
484 impl <T: EnumSetType, O: Into<EnumSet<T>>> BitXor<O> for EnumSet<T> {
486 fn bitxor(self, other: O) -> Self::Output {
487 self.symmetrical_difference(other.into())
491 impl <T: EnumSetType, O: Into<EnumSet<T>>> SubAssign<O> for EnumSet<T> {
492 fn sub_assign(&mut self, rhs: O) {
496 impl <T: EnumSetType, O: Into<EnumSet<T>>> BitAndAssign<O> for EnumSet<T> {
497 fn bitand_assign(&mut self, rhs: O) {
501 impl <T: EnumSetType, O: Into<EnumSet<T>>> BitOrAssign<O> for EnumSet<T> {
502 fn bitor_assign(&mut self, rhs: O) {
506 impl <T: EnumSetType, O: Into<EnumSet<T>>> BitXorAssign<O> for EnumSet<T> {
507 fn bitxor_assign(&mut self, rhs: O) {
512 impl <T: EnumSetType> Not for EnumSet<T> {
514 fn not(self) -> Self::Output {
519 impl <T: EnumSetType> From<T> for EnumSet<T> {
520 fn from(t: T) -> Self {
525 impl <T: EnumSetType> PartialEq<T> for EnumSet<T> {
526 fn eq(&self, other: &T) -> bool {
527 self.__priv_repr == EnumSet::only(*other).__priv_repr
530 impl <T: EnumSetType + Debug> Debug for EnumSet<T> {
531 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
532 let mut is_first = true;
533 f.write_str("EnumSet(")?;
534 for v in self.iter() {
535 if !is_first { f.write_str(" | ")?; }
544 impl <T: EnumSetType> Hash for EnumSet<T> {
545 fn hash<H: Hasher>(&self, state: &mut H) {
546 self.__priv_repr.hash(state)
549 impl <T: EnumSetType> PartialOrd for EnumSet<T> {
550 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
551 self.__priv_repr.partial_cmp(&other.__priv_repr)
554 impl <T: EnumSetType> Ord for EnumSet<T> {
555 fn cmp(&self, other: &Self) -> Ordering {
556 self.__priv_repr.cmp(&other.__priv_repr)
560 #[cfg(feature = "serde")]
561 impl <T: EnumSetType> Serialize for EnumSet<T> {
562 fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
563 T::serialize(*self, serializer)
567 #[cfg(feature = "serde")]
568 impl <'de, T: EnumSetType> Deserialize<'de> for EnumSet<T> {
569 fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
570 T::deserialize(deserializer)
574 /// The iterator used by [`EnumSet`]s.
575 #[derive(Clone, Debug)]
576 pub struct EnumSetIter<T: EnumSetType>(EnumSet<T>, u32);
577 impl <T: EnumSetType> Iterator for EnumSetIter<T> {
580 fn next(&mut self) -> Option<Self::Item> {
581 while self.1 < EnumSet::<T>::bit_width() {
584 if self.0.__priv_repr.has_bit(bit) {
585 return unsafe { Some(T::enum_from_u32(bit)) }
590 fn size_hint(&self) -> (usize, Option<usize>) {
591 let left = self.0.__priv_repr.count_remaining_ones(self.1);
596 impl<T: EnumSetType> Extend<T> for EnumSet<T> {
597 fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I) {
598 iter.into_iter().for_each(|v| { self.insert(v); });
602 impl<T: EnumSetType> FromIterator<T> for EnumSet<T> {
603 fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self {
604 let mut set = EnumSet::default();
610 impl<T: EnumSetType> Extend<EnumSet<T>> for EnumSet<T> {
611 fn extend<I: IntoIterator<Item = EnumSet<T>>>(&mut self, iter: I) {
612 iter.into_iter().for_each(|v| { self.insert_all(v); });
616 impl<T: EnumSetType> FromIterator<EnumSet<T>> for EnumSet<T> {
617 fn from_iter<I: IntoIterator<Item = EnumSet<T>>>(iter: I) -> Self {
618 let mut set = EnumSet::default();
624 /// Creates a EnumSet literal, which can be used in const contexts.
626 /// The syntax used is `enum_set!(Type::A | Type::B | Type::C)`. Each variant must be of the same
627 /// type, or a error will occur at compile-time.
629 /// This macro accepts trailing `|`s to allow easier use in other macros.
634 /// # use enumset::*;
635 /// # #[derive(EnumSetType, Debug)] enum Enum { A, B, C }
636 /// const CONST_SET: EnumSet<Enum> = enum_set!(Enum::A | Enum::B);
637 /// assert_eq!(CONST_SET, Enum::A | Enum::B);
640 /// This macro is strongly typed. For example, the following will not compile:
643 /// # use enumset::*;
644 /// # #[derive(EnumSetType, Debug)] enum Enum { A, B, C }
645 /// # #[derive(EnumSetType, Debug)] enum Enum2 { A, B, C }
646 /// let type_error = enum_set!(Enum::A | Enum2::B);
649 macro_rules! enum_set {
651 $crate::EnumSet { __priv_repr: 0 }
653 ($value:path $(|)*) => {
654 $value.__impl_enumset_internal__const_only()
656 ($value:path | $($rest:path)|* $(|)*) => {
658 #[allow(deprecated)] let value = $value.__impl_enumset_internal__const_only();
659 $(#[allow(deprecated)] let value = $rest.__impl_enumset_internal__const_merge(value);)*