]> git.lizzy.rs Git - enumset.git/blob - enumset/src/lib.rs
Use rustfmt to ensure consistant style.
[enumset.git] / enumset / src / lib.rs
1 #![no_std]
2 #![forbid(missing_docs)]
3 // The safety requirement is "use the procedural derive".
4 #![allow(clippy::missing_safety_doc)]
5
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.
8 //!
9 //! For serde support, enable the `serde` feature.
10 //!
11 //! # Defining enums for use with EnumSet
12 //!
13 //! Enums to be used with [`EnumSet`] should be defined using `#[derive(EnumSetType)]`:
14 //!
15 //! ```rust
16 //! # use enumset::*;
17 //! #[derive(EnumSetType, Debug)]
18 //! pub enum Enum {
19 //!    A, B, C, D, E, F, G,
20 //! }
21 //! ```
22 //!
23 //! For more information on more advanced use cases, see the documentation for
24 //! [`#[derive(EnumSetType)]`](./derive.EnumSetType.html).
25 //!
26 //! # Working with EnumSets
27 //!
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:
30 //!
31 //! ```rust
32 //! # use enumset::*;
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);
36 //! ```
37 //!
38 //! All bitwise operations you would expect to work on bitsets also work on both EnumSets and
39 //! enums with `#[derive(EnumSetType)]`:
40 //! ```rust
41 //! # use enumset::*;
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());
47 //!
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);
51 //!
52 //! // Difference of sets
53 //! assert_eq!((Enum::A | Enum::B | Enum::C) - Enum::B, Enum::A | Enum::C);
54 //!
55 //! // Complement of sets
56 //! assert_eq!(!(Enum::E | Enum::G), Enum::A | Enum::B | Enum::C | Enum::D | Enum::F);
57 //! ```
58 //!
59 //! The [`enum_set!`] macro allows you to create EnumSets in constant contexts:
60 //!
61 //! ```rust
62 //! # use enumset::*;
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);
66 //! ```
67 //!
68 //! Mutable operations on the [`EnumSet`] otherwise similarly to Rust's builtin sets:
69 //!
70 //! ```rust
71 //! # use enumset::*;
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);
79 //! ```
80
81 use core::cmp::Ordering;
82 use core::fmt;
83 use core::fmt::{Debug, Formatter};
84 use core::hash::{Hash, Hasher};
85 use core::iter::{FromIterator, Sum};
86 use core::ops::*;
87
88 #[doc(hidden)]
89 /// Everything in this module is internal API and may change at any time.
90 pub mod __internal {
91     use super::*;
92
93     /// A reexport of core to allow our macros to be generic to std vs core.
94     pub use ::core as core_export;
95
96     /// A reexport of serde so there is no requirement to depend on serde.
97     #[cfg(feature = "serde")]
98     pub use serde2 as serde;
99
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;
106
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;
111
112         /// Serializes the `EnumSet`.
113         ///
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;
123     }
124 }
125 #[cfg(feature = "serde")]
126 use crate::__internal::serde;
127 use crate::__internal::EnumSetTypePrivate;
128 #[cfg(feature = "serde")]
129 use crate::serde::{Deserialize, Serialize};
130
131 mod repr;
132 use crate::repr::EnumSetTypeRepr;
133
134 /// The procedural macro used to derive [`EnumSetType`], and allow enums to be used with
135 /// [`EnumSet`].
136 ///
137 /// It may be used with any enum with no data fields, at most 127 variants, and no variant
138 /// discriminators larger than 127.
139 ///
140 /// # Additional Impls
141 ///
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.
145 ///
146 /// A full list of traits implemented as is follows:
147 ///
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)]`.
154 ///
155 /// # Options
156 ///
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.
159 ///
160 /// A full list of options is as follows:
161 ///
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.
176 ///
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:
179 ///
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.
187 ///
188 /// # Examples
189 ///
190 /// Deriving a plain EnumSetType:
191 ///
192 /// ```rust
193 /// # use enumset::*;
194 /// #[derive(EnumSetType)]
195 /// pub enum Enum {
196 ///    A, B, C, D, E, F, G,
197 /// }
198 /// ```
199 ///
200 /// Deriving a sparse EnumSetType:
201 ///
202 /// ```rust
203 /// # use enumset::*;
204 /// #[derive(EnumSetType)]
205 /// pub enum SparseEnum {
206 ///    A = 10, B = 20, C = 30, D = 127,
207 /// }
208 /// ```
209 ///
210 /// Deriving an EnumSetType without adding ops:
211 ///
212 /// ```rust
213 /// # use enumset::*;
214 /// #[derive(EnumSetType)]
215 /// #[enumset(no_ops)]
216 /// pub enum NoOpsEnum {
217 ///    A, B, C, D, E, F, G,
218 /// }
219 /// ```
220 pub use enumset_derive::EnumSetType;
221
222 /// The trait used to define enum types that may be used with [`EnumSet`].
223 ///
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.
226 ///
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 {}
230
231 /// An [`EnumSetType`] for which [`EnumSet`]s have a guaranteed in-memory representation.
232 ///
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`.
236 ///
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>
242 {
243     /// The guaranteed representation.
244     type Repr: EnumSetTypeRepr;
245 }
246
247 /// An efficient set type for enums.
248 ///
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`).
252 ///
253 /// # Numeric representation
254 ///
255 /// `EnumSet` is internally implemented using integer types, and as such can be easily converted
256 /// from and to numbers.
257 ///
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.
261 ///
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`).
265 ///
266 /// # Serialization
267 ///
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
271 /// is enabled.
272 ///
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`.
278 ///
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.
282 ///
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.
286 ///
287 /// # FFI, Safety and `repr`
288 ///
289 /// If an enum type `T` is annotated with [`#[enumset(repr = "R")]`][derive@EnumSetType#options],
290 /// then several things happen:
291 ///
292 /// * `T` will implement <code>[EnumSetTypeWithRepr]&lt;Repr = R&gt;</code> in addition to
293 ///   [`EnumSetType`].
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`.
297 ///
298 /// That last guarantee makes it sound to send `EnumSet<T>` across an FFI boundary. For example:
299 ///
300 /// ```
301 /// # use enumset::*;
302 /// #
303 /// # mod ffi_impl {
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.
306 /// #     #[no_mangle]
307 /// #     extern "C" fn some_foreign_function(set: u32) -> u32 {
308 /// #         set & 0b100
309 /// #     }
310 /// # }
311 /// #
312 /// extern "C" {
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>;
316 /// }
317 ///
318 /// #[derive(Debug, EnumSetType)]
319 /// #[enumset(repr = "u32")]
320 /// enum MyEnum { A, B, C }
321 ///
322 /// let set: EnumSet<MyEnum> = enum_set!(MyEnum::A | MyEnum::C);
323 ///
324 /// let new_set: EnumSet<MyEnum> = unsafe { some_foreign_function(set) };
325 /// assert_eq!(new_set, enum_set!(MyEnum::C));
326 /// ```
327 ///
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)]
331 #[repr(transparent)]
332 pub struct EnumSet<T: EnumSetType> {
333     #[doc(hidden)]
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,
337 }
338 impl<T: EnumSetType> EnumSet<T> {
339     // Returns all bits valid for the enum
340     #[inline(always)]
341     fn all_bits() -> T::Repr {
342         T::ALL_BITS
343     }
344
345     /// Creates an empty `EnumSet`.
346     #[inline(always)]
347     pub fn new() -> Self {
348         EnumSet { __priv_repr: T::Repr::empty() }
349     }
350
351     /// Returns an `EnumSet` containing a single element.
352     #[inline(always)]
353     pub fn only(t: T) -> Self {
354         let mut set = Self::new();
355         set.insert(t);
356         set
357     }
358
359     /// Creates an empty `EnumSet`.
360     ///
361     /// This is an alias for [`EnumSet::new`].
362     #[inline(always)]
363     pub fn empty() -> Self {
364         Self::new()
365     }
366
367     /// Returns an `EnumSet` containing all valid variants of the enum.
368     #[inline(always)]
369     pub fn all() -> Self {
370         EnumSet { __priv_repr: Self::all_bits() }
371     }
372
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`).
375     ///
376     /// This is the same as [`EnumSet::variant_count`] except in enums with "sparse" variants.
377     /// (e.g. `enum Foo { A = 10, B = 20 }`)
378     #[inline(always)]
379     pub fn bit_width() -> u32 {
380         T::Repr::WIDTH - T::ALL_BITS.leading_zeros()
381     }
382
383     /// The number of valid variants that this type can contain.
384     ///
385     /// This is the same as [`EnumSet::bit_width`] except in enums with "sparse" variants.
386     /// (e.g. `enum Foo { A = 10, B = 20 }`)
387     #[inline(always)]
388     pub fn variant_count() -> u32 {
389         T::ALL_BITS.count_ones()
390     }
391
392     /// Returns the number of elements in this set.
393     #[inline(always)]
394     pub fn len(&self) -> usize {
395         self.__priv_repr.count_ones() as usize
396     }
397     /// Returns `true` if the set contains no elements.
398     #[inline(always)]
399     pub fn is_empty(&self) -> bool {
400         self.__priv_repr.is_empty()
401     }
402     /// Removes all elements from the set.
403     #[inline(always)]
404     pub fn clear(&mut self) {
405         self.__priv_repr = T::Repr::empty()
406     }
407
408     /// Returns `true` if `self` has no elements in common with `other`. This is equivalent to
409     /// checking for an empty intersection.
410     #[inline(always)]
411     pub fn is_disjoint(&self, other: Self) -> bool {
412         (*self & other).is_empty()
413     }
414     /// Returns `true` if the set is a superset of another, i.e., `self` contains at least all the
415     /// values in `other`.
416     #[inline(always)]
417     pub fn is_superset(&self, other: Self) -> bool {
418         (*self & other).__priv_repr == other.__priv_repr
419     }
420     /// Returns `true` if the set is a subset of another, i.e., `other` contains at least all
421     /// the values in `self`.
422     #[inline(always)]
423     pub fn is_subset(&self, other: Self) -> bool {
424         other.is_superset(*self)
425     }
426
427     /// Returns a set containing any elements present in either set.
428     #[inline(always)]
429     pub fn union(&self, other: Self) -> Self {
430         EnumSet { __priv_repr: self.__priv_repr | other.__priv_repr }
431     }
432     /// Returns a set containing every element present in both sets.
433     #[inline(always)]
434     pub fn intersection(&self, other: Self) -> Self {
435         EnumSet { __priv_repr: self.__priv_repr & other.__priv_repr }
436     }
437     /// Returns a set containing element present in `self` but not in `other`.
438     #[inline(always)]
439     pub fn difference(&self, other: Self) -> Self {
440         EnumSet { __priv_repr: self.__priv_repr.and_not(other.__priv_repr) }
441     }
442     /// Returns a set containing every element present in either `self` or `other`, but is not
443     /// present in both.
444     #[inline(always)]
445     pub fn symmetrical_difference(&self, other: Self) -> Self {
446         EnumSet { __priv_repr: self.__priv_repr ^ other.__priv_repr }
447     }
448     /// Returns a set containing all enum variants not in this set.
449     #[inline(always)]
450     pub fn complement(&self) -> Self {
451         EnumSet { __priv_repr: !self.__priv_repr & Self::all_bits() }
452     }
453
454     /// Checks whether this set contains a value.
455     #[inline(always)]
456     pub fn contains(&self, value: T) -> bool {
457         self.__priv_repr.has_bit(value.enum_into_u32())
458     }
459
460     /// Adds a value to this set.
461     ///
462     /// If the set did not have this value present, `true` is returned.
463     ///
464     /// If the set did have this value present, `false` is returned.
465     #[inline(always)]
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());
469         contains
470     }
471     /// Removes a value from this set. Returns whether the value was present in the set.
472     #[inline(always)]
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());
476         contains
477     }
478
479     /// Adds all elements in another set to this one.
480     #[inline(always)]
481     pub fn insert_all(&mut self, other: Self) {
482         self.__priv_repr = self.__priv_repr | other.__priv_repr
483     }
484     /// Removes all values in another set from this one.
485     #[inline(always)]
486     pub fn remove_all(&mut self, other: Self) {
487         self.__priv_repr = self.__priv_repr.and_not(other.__priv_repr);
488     }
489
490     /// Iterates the contents of the set in order from the least significant bit to the most
491     /// significant bit.
492     ///
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)
497     }
498
499     /// Returns a `T::Repr` representing the elements of this set.
500     ///
501     /// Unlike the other `as_*` methods, this method is zero-cost and guaranteed not to fail,
502     /// panic or truncate any bits.
503     ///
504     /// In order to use this method, the definition of `T` must have the `#[enumset(repr = "…")]`
505     /// annotation.
506     #[inline(always)]
507     pub fn as_repr(&self) -> <T as EnumSetTypeWithRepr>::Repr
508     where T: EnumSetTypeWithRepr {
509         self.__priv_repr
510     }
511
512     /// Constructs a bitset from a `T::Repr` without checking for invalid bits.
513     ///
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.
516     ///
517     /// In order to use this method, the definition of `T` must have the `#[enumset(repr = "…")]`
518     /// annotation.
519     ///
520     /// # Safety
521     ///
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.
524     #[inline(always)]
525     pub unsafe fn from_repr_unchecked(bits: <T as EnumSetTypeWithRepr>::Repr) -> Self
526     where T: EnumSetTypeWithRepr {
527         Self { __priv_repr: bits }
528     }
529
530     /// Constructs a bitset from a `T::Repr`.
531     ///
532     /// If a bit that doesn't correspond to an enum variant is set, this
533     /// method will panic.
534     ///
535     /// In order to use this method, the definition of `T` must have the `#[enumset(repr = "…")]`
536     /// annotation.
537     #[inline(always)]
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.")
541     }
542
543     /// Attempts to constructs a bitset from a `T::Repr`.
544     ///
545     /// If a bit that doesn't correspond to an enum variant is set, this
546     /// method will return `None`.
547     ///
548     /// In order to use this method, the definition of `T` must have the `#[enumset(repr = "…")]`
549     /// annotation.
550     #[inline(always)]
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 })
556         } else {
557             None
558         }
559     }
560
561     /// Constructs a bitset from a `T::Repr`, ignoring invalid variants.
562     ///
563     /// In order to use this method, the definition of `T` must have the `#[enumset(repr = "…")]`
564     /// annotation.
565     #[inline(always)]
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 }
571     }
572 }
573
574 /// Helper macro for generating conversion functions.
575 macro_rules! conversion_impls {
576     (
577         $(for_num!(
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
582         );)*
583     ) => {
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 \
588                      not fit in a `"]
589             #[doc = $underlying_str]
590             #[doc = "` or contains bits that do not correspond to an enum variant, this method \
591                      will panic."]
592             #[inline(always)]
593             pub fn $to(&self) -> $underlying {
594                 self.$try_to().expect("Bitset will not fit into this type.")
595             }
596
597             #[doc = "Tries to return a `"]
598             #[doc = $underlying_str]
599             #[doc = "` representing the elements of this set.\n\nIf the underlying bitset will \
600                      not fit in a `"]
601             #[doc = $underlying_str]
602             #[doc = "` or contains bits that do not correspond to an enum variant, this method \
603                      will instead return `None`."]
604             #[inline(always)]
605             pub fn $try_to(&self) -> Option<$underlying> {
606                 EnumSetTypeRepr::$to_fn_opt(&self.__priv_repr)
607             }
608
609             #[doc = "Returns a truncated `"]
610             #[doc = $underlying_str]
611             #[doc = "` representing the elements of this set.\n\nIf the underlying bitset will \
612                      not fit in a `"]
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."]
616             #[inline(always)]
617             pub fn $to_truncated(&self) -> $underlying {
618                 EnumSetTypeRepr::$to_fn(&self.__priv_repr)
619             }
620
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 \
624                      method will panic."]
625             #[inline(always)]
626             pub fn $from(bits: $underlying) -> Self {
627                 Self::$try_from(bits).expect("Bitset contains invalid variants.")
628             }
629
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`."]
634             #[inline(always)]
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 })
640                 } else {
641                     None
642                 })
643             }
644
645             #[doc = "Constructs a bitset from a `"]
646             #[doc = $underlying_str]
647             #[doc = "`, ignoring invalid variants."]
648             #[inline(always)]
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 }
653             }
654         )*}
655     }
656 }
657 conversion_impls! {
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);
671 }
672
673 impl<T: EnumSetType> Default for EnumSet<T> {
674     /// Returns an empty set.
675     fn default() -> Self {
676         Self::new()
677     }
678 }
679
680 impl<T: EnumSetType> IntoIterator for EnumSet<T> {
681     type Item = T;
682     type IntoIter = EnumSetIter<T>;
683
684     fn into_iter(self) -> Self::IntoIter {
685         self.iter()
686     }
687 }
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)
691     }
692 }
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)
696     }
697 }
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)
701     }
702 }
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)
706     }
707 }
708
709 impl<T: EnumSetType, O: Into<EnumSet<T>>> Sub<O> for EnumSet<T> {
710     type Output = Self;
711     #[inline(always)]
712     fn sub(self, other: O) -> Self::Output {
713         self.difference(other.into())
714     }
715 }
716 impl<T: EnumSetType, O: Into<EnumSet<T>>> BitAnd<O> for EnumSet<T> {
717     type Output = Self;
718     #[inline(always)]
719     fn bitand(self, other: O) -> Self::Output {
720         self.intersection(other.into())
721     }
722 }
723 impl<T: EnumSetType, O: Into<EnumSet<T>>> BitOr<O> for EnumSet<T> {
724     type Output = Self;
725     #[inline(always)]
726     fn bitor(self, other: O) -> Self::Output {
727         self.union(other.into())
728     }
729 }
730 impl<T: EnumSetType, O: Into<EnumSet<T>>> BitXor<O> for EnumSet<T> {
731     type Output = Self;
732     #[inline(always)]
733     fn bitxor(self, other: O) -> Self::Output {
734         self.symmetrical_difference(other.into())
735     }
736 }
737
738 impl<T: EnumSetType, O: Into<EnumSet<T>>> SubAssign<O> for EnumSet<T> {
739     #[inline(always)]
740     fn sub_assign(&mut self, rhs: O) {
741         *self = *self - rhs;
742     }
743 }
744 impl<T: EnumSetType, O: Into<EnumSet<T>>> BitAndAssign<O> for EnumSet<T> {
745     #[inline(always)]
746     fn bitand_assign(&mut self, rhs: O) {
747         *self = *self & rhs;
748     }
749 }
750 impl<T: EnumSetType, O: Into<EnumSet<T>>> BitOrAssign<O> for EnumSet<T> {
751     #[inline(always)]
752     fn bitor_assign(&mut self, rhs: O) {
753         *self = *self | rhs;
754     }
755 }
756 impl<T: EnumSetType, O: Into<EnumSet<T>>> BitXorAssign<O> for EnumSet<T> {
757     #[inline(always)]
758     fn bitxor_assign(&mut self, rhs: O) {
759         *self = *self ^ rhs;
760     }
761 }
762
763 impl<T: EnumSetType> Not for EnumSet<T> {
764     type Output = Self;
765     #[inline(always)]
766     fn not(self) -> Self::Output {
767         self.complement()
768     }
769 }
770
771 impl<T: EnumSetType> From<T> for EnumSet<T> {
772     fn from(t: T) -> Self {
773         EnumSet::only(t)
774     }
775 }
776
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
780     }
781 }
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() {
787             if !is_first {
788                 f.write_str(" | ")?;
789             }
790             is_first = false;
791             v.fmt(f)?;
792         }
793         f.write_str(")")?;
794         Ok(())
795     }
796 }
797
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)
802     }
803 }
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)
807     }
808 }
809 impl<T: EnumSetType> Ord for EnumSet<T> {
810     fn cmp(&self, other: &Self) -> Ordering {
811         self.__priv_repr.cmp(&other.__priv_repr)
812     }
813 }
814
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)
819     }
820 }
821
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)
826     }
827 }
828
829 /// The iterator used by [`EnumSet`]s.
830 #[derive(Clone, Debug)]
831 pub struct EnumSetIter<T: EnumSetType> {
832     set: EnumSet<T>,
833 }
834 impl<T: EnumSetType> EnumSetIter<T> {
835     fn new(set: EnumSet<T>) -> EnumSetIter<T> {
836         EnumSetIter { set }
837     }
838 }
839
840 impl<T: EnumSetType> Iterator for EnumSetIter<T> {
841     type Item = T;
842
843     fn next(&mut self) -> Option<Self::Item> {
844         if self.set.is_empty() {
845             None
846         } else {
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)) }
850         }
851     }
852     fn size_hint(&self) -> (usize, Option<usize>) {
853         let left = self.set.len();
854         (left, Some(left))
855     }
856 }
857
858 impl<T: EnumSetType> DoubleEndedIterator for EnumSetIter<T> {
859     fn next_back(&mut self) -> Option<Self::Item> {
860         if self.set.is_empty() {
861             None
862         } else {
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)) }
866         }
867     }
868 }
869
870 impl<T: EnumSetType> ExactSizeIterator for EnumSetIter<T> {}
871
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| {
875             self.insert(v);
876         });
877     }
878 }
879
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();
883         set.extend(iter);
884         set
885     }
886 }
887
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| {
891             self.insert_all(v);
892         });
893     }
894 }
895
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();
899         set.extend(iter);
900         set
901     }
902 }
903
904 /// Creates a EnumSet literal, which can be used in const contexts.
905 ///
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.
908 ///
909 /// This macro accepts trailing `|`s to allow easier use in other macros.
910 ///
911 /// # Examples
912 ///
913 /// ```rust
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);
918 /// ```
919 ///
920 /// This macro is strongly typed. For example, the following will not compile:
921 ///
922 /// ```compile_fail
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);
927 /// ```
928 #[macro_export]
929 macro_rules! enum_set {
930     ($(|)*) => {
931         $crate::EnumSet { __priv_repr: 0 }
932     };
933     ($value:path $(|)*) => {
934         {
935             #[allow(deprecated)] let value = $value.__impl_enumset_internal__const_only();
936             value
937         }
938     };
939     ($value:path | $($rest:path)|* $(|)*) => {
940         {
941             #[allow(deprecated)] let value = $value.__impl_enumset_internal__const_only();
942             $(#[allow(deprecated)] let value = $rest.__impl_enumset_internal__const_merge(value);)*
943             value
944         }
945     };
946 }