]> git.lizzy.rs Git - enumset.git/blob - enumset/src/lib.rs
Add `repr` option to derive.
[enumset.git] / enumset / src / lib.rs
1 #![no_std]
2 #![forbid(missing_docs)]
3
4 // The safety requirement is "use the procedural derive".
5 #![allow(clippy::missing_safety_doc)]
6
7 //! A library for defining enums that can be used in compact bit sets. It supports enums up to 128
8 //! variants, and has a macro to use these sets in constants.
9 //!
10 //! For serde support, enable the `serde` feature.
11 //!
12 //! # Defining enums for use with EnumSet
13 //!
14 //! Enums to be used with [`EnumSet`] should be defined using `#[derive(EnumSetType)]`:
15 //!
16 //! ```rust
17 //! # use enumset::*;
18 //! #[derive(EnumSetType, Debug)]
19 //! pub enum Enum {
20 //!    A, B, C, D, E, F, G,
21 //! }
22 //! ```
23 //!
24 //! For more information on more advanced use cases, see the documentation for
25 //! [`#[derive(EnumSetType)]`](./derive.EnumSetType.html).
26 //!
27 //! # Working with EnumSets
28 //!
29 //! EnumSets can be constructed via [`EnumSet::new()`] like a normal set. In addition,
30 //! `#[derive(EnumSetType)]` creates operator overloads that allow you to create EnumSets like so:
31 //!
32 //! ```rust
33 //! # use enumset::*;
34 //! # #[derive(EnumSetType, Debug)] pub enum Enum { A, B, C, D, E, F, G }
35 //! let new_set = Enum::A | Enum::C | Enum::G;
36 //! assert_eq!(new_set.len(), 3);
37 //! ```
38 //!
39 //! All bitwise operations you would expect to work on bitsets also work on both EnumSets and
40 //! enums with `#[derive(EnumSetType)]`:
41 //! ```rust
42 //! # use enumset::*;
43 //! # #[derive(EnumSetType, Debug)] pub enum Enum { A, B, C, D, E, F, G }
44 //! // Intersection of sets
45 //! assert_eq!((Enum::A | Enum::B) & Enum::C, EnumSet::empty());
46 //! assert_eq!((Enum::A | Enum::B) & Enum::A, Enum::A);
47 //! assert_eq!(Enum::A & Enum::B, EnumSet::empty());
48 //!
49 //! // Symmetric difference of sets
50 //! assert_eq!((Enum::A | Enum::B) ^ (Enum::B | Enum::C), Enum::A | Enum::C);
51 //! assert_eq!(Enum::A ^ Enum::C, Enum::A | Enum::C);
52 //!
53 //! // Difference of sets
54 //! assert_eq!((Enum::A | Enum::B | Enum::C) - Enum::B, Enum::A | Enum::C);
55 //!
56 //! // Complement of sets
57 //! assert_eq!(!(Enum::E | Enum::G), Enum::A | Enum::B | Enum::C | Enum::D | Enum::F);
58 //! ```
59 //!
60 //! The [`enum_set!`] macro allows you to create EnumSets in constant contexts:
61 //!
62 //! ```rust
63 //! # use enumset::*;
64 //! # #[derive(EnumSetType, Debug)] pub enum Enum { A, B, C, D, E, F, G }
65 //! const CONST_SET: EnumSet<Enum> = enum_set!(Enum::A | Enum::B);
66 //! assert_eq!(CONST_SET, Enum::A | Enum::B);
67 //! ```
68 //!
69 //! Mutable operations on the [`EnumSet`] otherwise similarly to Rust's builtin sets:
70 //!
71 //! ```rust
72 //! # use enumset::*;
73 //! # #[derive(EnumSetType, Debug)] pub enum Enum { A, B, C, D, E, F, G }
74 //! let mut set = EnumSet::new();
75 //! set.insert(Enum::A);
76 //! set.insert_all(Enum::E | Enum::G);
77 //! assert!(set.contains(Enum::A));
78 //! assert!(!set.contains(Enum::B));
79 //! assert_eq!(set, Enum::A | Enum::E | Enum::G);
80 //! ```
81
82 use core::cmp::Ordering;
83 use core::fmt;
84 use core::fmt::{Debug, Formatter};
85 use core::hash::{Hash, Hasher};
86 use core::iter::{FromIterator, Sum};
87 use core::ops::*;
88
89 #[doc(hidden)]
90 /// Everything in this module is internal API and may change at any time.
91 pub mod __internal {
92     use super::*;
93
94     /// A reexport of core to allow our macros to be generic to std vs core.
95     pub use ::core as core_export;
96
97     /// A reexport of serde so there is no requirement to depend on serde.
98     #[cfg(feature = "serde")] 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 use crate::__internal::EnumSetTypePrivate;
126 #[cfg(feature = "serde")] use crate::__internal::serde;
127 #[cfg(feature = "serde")] use crate::serde::{Serialize, Deserialize};
128
129 mod repr;
130 use crate::repr::EnumSetTypeRepr;
131
132 /// The procedural macro used to derive [`EnumSetType`], and allow enums to be used with
133 /// [`EnumSet`].
134 ///
135 /// It may be used with any enum with no data fields, at most 127 variants, and no variant
136 /// discriminators larger than 127.
137 ///
138 /// # Additional Impls
139 ///
140 /// In addition to the implementation of `EnumSetType`, this procedural macro creates multiple
141 /// other impls that are either required for the macro to work, or make the procedural macro more
142 /// ergonomic to use.
143 ///
144 /// A full list of traits implemented as is follows:
145 ///
146 /// * [`Copy`], [`Clone`], [`Eq`], [`PartialEq`] implementations are created to allow `EnumSet`
147 ///   to function properly. These automatic implementations may be suppressed using
148 ///   `#[enumset(no_super_impls)]`, but these traits must still be implemented in another way.
149 /// * [`PartialEq`], [`Sub`], [`BitAnd`], [`BitOr`], [`BitXor`], and [`Not`] implementations are
150 ///   created to allow the crate to be used more ergonomically in expressions. These automatic
151 ///   implementations may be suppressed using `#[enumset(no_ops)]`.
152 ///
153 /// # Options
154 ///
155 /// Options are given with `#[enumset(foo)]` annotations attached to the same enum as the derive.
156 /// Multiple options may be given in the same annotation using the `#[enumset(foo, bar)]` syntax.
157 ///
158 /// A full list of options is as follows:
159 ///
160 /// * `#[enumset(no_super_impls)]` prevents the derive from creating implementations required for
161 ///   [`EnumSet`] to function. When this attribute is specified, implementations of [`Copy`],
162 ///   [`Clone`], [`Eq`], and [`PartialEq`]. This can be useful if you are using a code generator
163 ///   that already derives these traits. These impls should function identically to the
164 ///   automatically derived versions, or unintentional behavior may be a result.
165 /// * `#[enumset(no_ops)` prevents the derive from implementing any operator traits.
166 /// * `#[enumset(crate_name = "enumset2")]` may be used to change the name of the `enumset` crate
167 ///   used in the generated code. When the `std` feature is enabled, enumset parses `Cargo.toml`
168 ///   to determine the name of the crate, and this flag is unnecessary.
169 /// * `#[enumset(repr = "u8")]` may be used to specify the in-memory representation of `EnumSet`s
170 ///   of this enum type. The effects of this are described in [the `EnumSet` documentation under
171 ///   “FFI, Safety and `repr`”][EnumSet#ffi-safety-and-repr]. Allowed types are `u8`, `u16`, `u32`,
172 ///   `u64` and `u128`. If this is not used, then the derive macro will choose a type to best fit
173 ///   the enum, but there are no guarantees about which type will be chosen.
174 ///
175 /// When the `serde` feature is used, the following features may also be specified. These options
176 /// may be used (with no effect) when building without the feature enabled:
177 ///
178 /// * `#[enumset(serialize_repr = "u8")]` may be used to specify the integer type used to serialize
179 ///   the underlying bitset.
180 /// * `#[enumset(serialize_as_list)]` may be used to serialize the bitset as a list of enum
181 ///   variants instead of an integer. This requires [`Deserialize`] and [`Serialize`] be
182 ///   implemented on the enum.
183 /// * `#[enumset(serialize_deny_unknown)]` causes the generated deserializer to return an error
184 ///   for unknown bits instead of silently ignoring them.
185 ///
186 /// # Examples
187 ///
188 /// Deriving a plain EnumSetType:
189 ///
190 /// ```rust
191 /// # use enumset::*;
192 /// #[derive(EnumSetType)]
193 /// pub enum Enum {
194 ///    A, B, C, D, E, F, G,
195 /// }
196 /// ```
197 ///
198 /// Deriving a sparse EnumSetType:
199 ///
200 /// ```rust
201 /// # use enumset::*;
202 /// #[derive(EnumSetType)]
203 /// pub enum SparseEnum {
204 ///    A = 10, B = 20, C = 30, D = 127,
205 /// }
206 /// ```
207 ///
208 /// Deriving an EnumSetType without adding ops:
209 ///
210 /// ```rust
211 /// # use enumset::*;
212 /// #[derive(EnumSetType)]
213 /// #[enumset(no_ops)]
214 /// pub enum NoOpsEnum {
215 ///    A, B, C, D, E, F, G,
216 /// }
217 /// ```
218 pub use enumset_derive::EnumSetType;
219
220 /// The trait used to define enum types that may be used with [`EnumSet`].
221 ///
222 /// This trait must be impelmented using `#[derive(EnumSetType)]`, is not public API, and its
223 /// internal structure may change at any time with no warning.
224 ///
225 /// For full documentation on the procedural derive and its options, see
226 /// [`#[derive(EnumSetType)]`](./derive.EnumSetType.html).
227 pub unsafe trait EnumSetType: Copy + Eq + EnumSetTypePrivate { }
228
229 /// An [`EnumSetType`] for which [`EnumSet`]s have a guaranteed in-memory representation.
230 ///
231 /// An implementation of this trait is generated by using
232 /// [`#[derive(EnumSetType)]`](./derive.EnumSetType.html) with the annotation
233 /// `#[enumset(repr = "…")]`, where `…` is `u8`, `u16`, `u32`, `u64` or `u128`.
234 ///
235 /// For any type `T` that implements this trait, the in-memory representation of `EnumSet<T>`
236 /// is guaranteed to be `Repr`. This guarantee is useful for FFI. See [the `EnumSet` documentation
237 /// under “FFI, Safety and `repr`”][EnumSet#ffi-safety-and-repr] for an example.
238 pub unsafe trait EnumSetTypeWithRepr: EnumSetType + EnumSetTypePrivate<Repr = <Self as EnumSetTypeWithRepr>::Repr> {
239     /// The guaranteed representation.
240     type Repr: EnumSetTypeRepr;
241 }
242
243 /// An efficient set type for enums.
244 ///
245 /// It is implemented using a bitset stored using the smallest integer that can fit all bits
246 /// in the underlying enum. In general, an enum variant with a discriminator of `n` is stored in
247 /// the nth least significant bit (corresponding with a mask of, e.g. `1 << enum as u32`).
248 ///
249 /// # Numeric representation
250 ///
251 /// `EnumSet` is internally implemented using integer types, and as such can be easily converted
252 /// from and to numbers.
253 ///
254 /// Each bit of the underlying integer corresponds to at most one particular enum variant. If the
255 /// corresponding bit for a variant is set, it present in the set. Bits that do not correspond to
256 /// any variant are always unset.
257 ///
258 /// By default, each enum variant is stored in a bit corresponding to its discriminator. An enum
259 /// variant with a discriminator of `n` is stored in the `n + 1`th least significant bit
260 /// (corresponding to a mask of e.g. `1 << enum as u32`).
261 ///
262 /// # Serialization
263 ///
264 /// When the `serde` feature is enabled, `EnumSet`s can be serialized and deserialized using
265 /// the `serde` crate. The exact serialization format can be controlled with additional attributes
266 /// on the enum type. These attributes are valid regardless of whether the `serde` feature
267 /// is enabled.
268 ///
269 /// By default, `EnumSet`s serialize by directly writing out the underlying bitset as an integer
270 /// of the smallest type that can fit in the underlying enum. You can add a
271 /// `#[enumset(serialize_repr = "u8")]` attribute to your enum to control the integer type used
272 /// for serialization. This can be important for avoiding unintentional breaking changes when
273 /// `EnumSet`s are serialized with formats like `bincode`.
274 ///
275 /// By default, unknown bits are ignored and silently removed from the bitset. To override thris
276 /// behavior, you can add a `#[enumset(serialize_deny_unknown)]` attribute. This will cause
277 /// deserialization to fail if an invalid bit is set.
278 ///
279 /// In addition, the `#[enumset(serialize_as_list)]` attribute causes the `EnumSet` to be
280 /// instead serialized as a list of enum variants. This requires your enum type implement
281 /// [`Serialize`] and [`Deserialize`]. Note that this is a breaking change.
282 ///
283 /// # FFI, Safety and `repr`
284 ///
285 /// If an enum type `T` is annotated with [`#[enumset(repr = "R")]`][derive@EnumSetType#options], then
286 /// several things happen:
287 ///
288 /// * `T` will implement <code>[EnumSetTypeWithRepr]&lt;Repr = R&gt;</code> in addition to
289 ///   [`EnumSetType`].
290 /// * The `EnumSet` methods with `repr` in their name, such as [`as_repr`][EnumSet::as_repr] and
291 ///   [`from_repr`][EnumSet::from_repr], will be available for `EnumSet<T>`.
292 /// * The in-memory representation of `EnumSet<T>` is guaranteed to be `R`.
293 ///
294 /// That last guarantee makes it sound to send `EnumSet<T>` across an FFI boundary. For example:
295 ///
296 /// ```
297 /// # use enumset::*;
298 /// #
299 /// # mod ffi_impl {
300 /// #     // This example “foreign” function is actually written in Rust, but for the sake
301 /// #     // of example, we'll pretend it's written in C.
302 /// #     #[no_mangle]
303 /// #     extern "C" fn some_foreign_function(set: u32) -> u32 {
304 /// #         set & 0b100
305 /// #     }
306 /// # }
307 /// #
308 /// extern "C" {
309 ///     // This function is written in C like:
310 ///     // uint32_t some_foreign_function(uint32_t set) { … }
311 ///     fn some_foreign_function(set: EnumSet<MyEnum>) -> EnumSet<MyEnum>;
312 /// }
313 ///
314 /// #[derive(Debug, EnumSetType)]
315 /// #[enumset(repr = "u32")]
316 /// enum MyEnum { A, B, C }
317 ///
318 /// let set: EnumSet<MyEnum> = enum_set!(MyEnum::A | MyEnum::C);
319 ///
320 /// let new_set: EnumSet<MyEnum> = unsafe { some_foreign_function(set) };
321 /// assert_eq!(new_set, enum_set!(MyEnum::C));
322 /// ```
323 ///
324 /// When an `EnumSet<T>` is received via FFI, all bits that don't correspond to an enum variant
325 /// of `T` must be set to 0. Behavior is **undefined** if any of these bits are set to 1.
326 #[derive(Copy, Clone, PartialEq, Eq)]
327 #[repr(transparent)]
328 pub struct EnumSet<T: EnumSetType> {
329     #[doc(hidden)]
330     /// This is public due to the [`enum_set!`] macro.
331     /// This is **NOT** public API and may change at any time.
332     pub __priv_repr: T::Repr
333 }
334 impl <T: EnumSetType> EnumSet<T> {
335     // Returns all bits valid for the enum
336     #[inline(always)]
337     fn all_bits() -> T::Repr {
338         T::ALL_BITS
339     }
340
341     /// Creates an empty `EnumSet`.
342     #[inline(always)]
343     pub fn new() -> Self {
344         EnumSet { __priv_repr: T::Repr::empty() }
345     }
346
347     /// Returns an `EnumSet` containing a single element.
348     #[inline(always)]
349     pub fn only(t: T) -> Self {
350         let mut set = Self::new();
351         set.insert(t);
352         set
353     }
354
355     /// Creates an empty `EnumSet`.
356     ///
357     /// This is an alias for [`EnumSet::new`].
358     #[inline(always)]
359     pub fn empty() -> Self {
360         Self::new()
361     }
362
363     /// Returns an `EnumSet` containing all valid variants of the enum.
364     #[inline(always)]
365     pub fn all() -> Self {
366         EnumSet { __priv_repr: Self::all_bits() }
367     }
368
369     /// Total number of bits used by this type. Note that the actual amount of space used is
370     /// rounded up to the next highest integer type (`u8`, `u16`, `u32`, `u64`, or `u128`).
371     ///
372     /// This is the same as [`EnumSet::variant_count`] except in enums with "sparse" variants.
373     /// (e.g. `enum Foo { A = 10, B = 20 }`)
374     #[inline(always)]
375     pub fn bit_width() -> u32 {
376         T::Repr::WIDTH - T::ALL_BITS.leading_zeros()
377     }
378
379     /// The number of valid variants that this type can contain.
380     ///
381     /// This is the same as [`EnumSet::bit_width`] except in enums with "sparse" variants.
382     /// (e.g. `enum Foo { A = 10, B = 20 }`)
383     #[inline(always)]
384     pub fn variant_count() -> u32 {
385         T::ALL_BITS.count_ones()
386     }
387
388     /// Returns the number of elements in this set.
389     #[inline(always)]
390     pub fn len(&self) -> usize {
391         self.__priv_repr.count_ones() as usize
392     }
393     /// Returns `true` if the set contains no elements.
394     #[inline(always)]
395     pub fn is_empty(&self) -> bool {
396         self.__priv_repr.is_empty()
397     }
398     /// Removes all elements from the set.
399     #[inline(always)]
400     pub fn clear(&mut self) {
401         self.__priv_repr = T::Repr::empty()
402     }
403
404     /// Returns `true` if `self` has no elements in common with `other`. This is equivalent to
405     /// checking for an empty intersection.
406     #[inline(always)]
407     pub fn is_disjoint(&self, other: Self) -> bool {
408         (*self & other).is_empty()
409     }
410     /// Returns `true` if the set is a superset of another, i.e., `self` contains at least all the
411     /// values in `other`.
412     #[inline(always)]
413     pub fn is_superset(&self, other: Self) -> bool {
414         (*self & other).__priv_repr == other.__priv_repr
415     }
416     /// Returns `true` if the set is a subset of another, i.e., `other` contains at least all
417     /// the values in `self`.
418     #[inline(always)]
419     pub fn is_subset(&self, other: Self) -> bool {
420         other.is_superset(*self)
421     }
422
423     /// Returns a set containing any elements present in either set.
424     #[inline(always)]
425     pub fn union(&self, other: Self) -> Self {
426         EnumSet { __priv_repr: self.__priv_repr | other.__priv_repr }
427     }
428     /// Returns a set containing every element present in both sets.
429     #[inline(always)]
430     pub fn intersection(&self, other: Self) -> Self {
431         EnumSet { __priv_repr: self.__priv_repr & other.__priv_repr }
432     }
433     /// Returns a set containing element present in `self` but not in `other`.
434     #[inline(always)]
435     pub fn difference(&self, other: Self) -> Self {
436         EnumSet { __priv_repr: self.__priv_repr.and_not(other.__priv_repr) }
437     }
438     /// Returns a set containing every element present in either `self` or `other`, but is not
439     /// present in both.
440     #[inline(always)]
441     pub fn symmetrical_difference(&self, other: Self) -> Self {
442         EnumSet { __priv_repr: self.__priv_repr ^ other.__priv_repr }
443     }
444     /// Returns a set containing all enum variants not in this set.
445     #[inline(always)]
446     pub fn complement(&self) -> Self {
447         EnumSet { __priv_repr: !self.__priv_repr & Self::all_bits() }
448     }
449
450     /// Checks whether this set contains a value.
451     #[inline(always)]
452     pub fn contains(&self, value: T) -> bool {
453         self.__priv_repr.has_bit(value.enum_into_u32())
454     }
455
456     /// Adds a value to this set.
457     ///
458     /// If the set did not have this value present, `true` is returned.
459     ///
460     /// If the set did have this value present, `false` is returned.
461     #[inline(always)]
462     pub fn insert(&mut self, value: T) -> bool {
463         let contains = !self.contains(value);
464         self.__priv_repr.add_bit(value.enum_into_u32());
465         contains
466     }
467     /// Removes a value from this set. Returns whether the value was present in the set.
468     #[inline(always)]
469     pub fn remove(&mut self, value: T) -> bool {
470         let contains = self.contains(value);
471         self.__priv_repr.remove_bit(value.enum_into_u32());
472         contains
473     }
474
475     /// Adds all elements in another set to this one.
476     #[inline(always)]
477     pub fn insert_all(&mut self, other: Self) {
478         self.__priv_repr = self.__priv_repr | other.__priv_repr
479     }
480     /// Removes all values in another set from this one.
481     #[inline(always)]
482     pub fn remove_all(&mut self, other: Self) {
483         self.__priv_repr = self.__priv_repr.and_not(other.__priv_repr);
484     }
485
486     /// Iterates the contents of the set in order from the least significant bit to the most
487     /// significant bit.
488     ///
489     /// Note that iterator invalidation is impossible as the iterator contains a copy of this type,
490     /// rather than holding a reference to it.
491     pub fn iter(&self) -> EnumSetIter<T> {
492         EnumSetIter::new(*self)
493     }
494
495     /// Returns a `T::Repr` representing the elements of this set.
496     ///
497     /// Unlike the other `as_*` methods, this method is zero-cost and guaranteed not to fail,
498     /// panic or truncate any bits.
499     ///
500     /// In order to use this method, the definition of `T` must have the `#[enumset(repr = "…")]`
501     /// annotation.
502     #[inline(always)]
503     pub fn as_repr(&self) -> <T as EnumSetTypeWithRepr>::Repr
504     where
505         T: EnumSetTypeWithRepr,
506     {
507         self.__priv_repr
508     }
509
510     /// Constructs a bitset from a `T::Repr` without checking for invalid bits.
511     ///
512     /// Unlike the other `from_*` methods, this method is zero-cost and guaranteed not to fail,
513     /// panic or truncate any bits, provided the conditions under “Safety” are upheld.
514     ///
515     /// In order to use this method, the definition of `T` must have the `#[enumset(repr = "…")]`
516     /// annotation.
517     ///
518     /// # Safety
519     ///
520     /// All bits in the provided parameter `bits` that don't correspond to an enum variant of
521     /// `T` must be set to 0. Behavior is **undefined** if any of these bits are set to 1.
522     #[inline(always)]
523     pub unsafe fn from_repr_unchecked(bits: <T as EnumSetTypeWithRepr>::Repr) -> Self
524     where
525         T: EnumSetTypeWithRepr,
526     {
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
540         T: EnumSetTypeWithRepr,
541     {
542         Self::try_from_repr(bits).expect("Bitset contains invalid variants.")
543     }
544
545     /// Attempts to constructs a bitset from a `T::Repr`.
546     ///
547     /// If a bit that doesn't correspond to an enum variant is set, this
548     /// method will return `None`.
549     ///
550     /// In order to use this method, the definition of `T` must have the `#[enumset(repr = "…")]`
551     /// annotation.
552     #[inline(always)]
553     pub fn try_from_repr(bits: <T as EnumSetTypeWithRepr>::Repr) -> Option<Self>
554     where
555         T: EnumSetTypeWithRepr,
556     {
557         let mask = Self::all().__priv_repr;
558         if bits.and_not(mask).is_empty() {
559             Some(EnumSet { __priv_repr: bits })
560         } else {
561             None
562         }
563     }
564
565     /// Constructs a bitset from a `T::Repr`, ignoring invalid variants.
566     ///
567     /// In order to use this method, the definition of `T` must have the `#[enumset(repr = "…")]`
568     /// annotation.
569     #[inline(always)]
570     pub fn from_repr_truncated(bits: <T as EnumSetTypeWithRepr>::Repr) -> Self
571     where
572         T: EnumSetTypeWithRepr,
573     {
574         let mask = Self::all().as_repr();
575         let bits = bits & mask;
576         EnumSet { __priv_repr: bits }
577     }
578 }
579
580 /// Helper macro for generating conversion functions.
581 macro_rules! conversion_impls {
582     (
583         $(for_num!(
584             $underlying:ty, $underlying_str:expr,
585             $from_fn:ident $to_fn:ident $from_fn_opt:ident $to_fn_opt:ident,
586             $from:ident $try_from:ident $from_truncated:ident
587             $to:ident $try_to:ident $to_truncated:ident
588         );)*
589     ) => {
590         impl <T : EnumSetType> EnumSet<T> {$(
591             #[doc = "Returns a `"]
592             #[doc = $underlying_str]
593             #[doc = "` representing the elements of this set.\n\nIf the underlying bitset will \
594                      not fit in a `"]
595             #[doc = $underlying_str]
596             #[doc = "` or contains bits that do not correspond to an enum variant, this method \
597                      will panic."]
598             #[inline(always)]
599             pub fn $to(&self) -> $underlying {
600                 self.$try_to().expect("Bitset will not fit into this type.")
601             }
602
603             #[doc = "Tries to return a `"]
604             #[doc = $underlying_str]
605             #[doc = "` representing the elements of this set.\n\nIf the underlying bitset will \
606                      not fit in a `"]
607             #[doc = $underlying_str]
608             #[doc = "` or contains bits that do not correspond to an enum variant, this method \
609                      will instead return `None`."]
610             #[inline(always)]
611             pub fn $try_to(&self) -> Option<$underlying> {
612                 EnumSetTypeRepr::$to_fn_opt(&self.__priv_repr)
613             }
614
615             #[doc = "Returns a truncated `"]
616             #[doc = $underlying_str]
617             #[doc = "` representing the elements of this set.\n\nIf the underlying bitset will \
618                      not fit in a `"]
619             #[doc = $underlying_str]
620             #[doc = "`, this method will truncate any bits that don't fit or do not correspond \
621                      to an enum variant."]
622             #[inline(always)]
623             pub fn $to_truncated(&self) -> $underlying {
624                 EnumSetTypeRepr::$to_fn(&self.__priv_repr)
625             }
626
627             #[doc = "Constructs a bitset from a `"]
628             #[doc = $underlying_str]
629             #[doc = "`.\n\nIf a bit that doesn't correspond to an enum variant is set, this \
630                      method will panic."]
631             #[inline(always)]
632             pub fn $from(bits: $underlying) -> Self {
633                 Self::$try_from(bits).expect("Bitset contains invalid variants.")
634             }
635
636             #[doc = "Attempts to constructs a bitset from a `"]
637             #[doc = $underlying_str]
638             #[doc = "`.\n\nIf a bit that doesn't correspond to an enum variant is set, this \
639                      method will return `None`."]
640             #[inline(always)]
641             pub fn $try_from(bits: $underlying) -> Option<Self> {
642                 let bits = T::Repr::$from_fn_opt(bits);
643                 let mask = Self::all().__priv_repr;
644                 bits.and_then(|bits| if bits.and_not(mask).is_empty() {
645                     Some(EnumSet { __priv_repr: bits })
646                 } else {
647                     None
648                 })
649             }
650
651             #[doc = "Constructs a bitset from a `"]
652             #[doc = $underlying_str]
653             #[doc = "`, ignoring invalid variants."]
654             #[inline(always)]
655             pub fn $from_truncated(bits: $underlying) -> Self {
656                 let mask = Self::all().$to_truncated();
657                 let bits = <T::Repr as EnumSetTypeRepr>::$from_fn(bits & mask);
658                 EnumSet { __priv_repr: bits }
659             }
660         )*}
661     }
662 }
663 conversion_impls! {
664     for_num!(u8, "u8", from_u8 to_u8 from_u8_opt to_u8_opt,
665              from_u8 try_from_u8 from_u8_truncated as_u8 try_as_u8 as_u8_truncated);
666     for_num!(u16, "u16", from_u16 to_u16 from_u16_opt to_u16_opt,
667              from_u16 try_from_u16 from_u16_truncated as_u16 try_as_u16 as_u16_truncated);
668     for_num!(u32, "u32", from_u32 to_u32 from_u32_opt to_u32_opt,
669              from_u32 try_from_u32 from_u32_truncated as_u32 try_as_u32 as_u32_truncated);
670     for_num!(u64, "u64", from_u64 to_u64 from_u64_opt to_u64_opt,
671              from_u64 try_from_u64 from_u64_truncated as_u64 try_as_u64 as_u64_truncated);
672     for_num!(u128, "u128", from_u128 to_u128 from_u128_opt to_u128_opt,
673              from_u128 try_from_u128 from_u128_truncated as_u128 try_as_u128 as_u128_truncated);
674     for_num!(usize, "usize", from_usize to_usize from_usize_opt to_usize_opt,
675              from_usize try_from_usize from_usize_truncated
676              as_usize try_as_usize as_usize_truncated);
677 }
678
679 impl <T: EnumSetType> Default for EnumSet<T> {
680     /// Returns an empty set.
681     fn default() -> Self {
682         Self::new()
683     }
684 }
685
686 impl <T: EnumSetType> IntoIterator for EnumSet<T> {
687     type Item = T;
688     type IntoIter = EnumSetIter<T>;
689
690     fn into_iter(self) -> Self::IntoIter {
691         self.iter()
692     }
693 }
694 impl <T: EnumSetType> Sum for EnumSet<T> {
695     fn sum<I: Iterator<Item=Self>>(iter: I) -> Self {
696         iter.fold(EnumSet::empty(), |a, v| a | v)
697     }
698 }
699 impl <'a, T: EnumSetType> Sum<&'a EnumSet<T>> for EnumSet<T> {
700     fn sum<I: Iterator<Item=&'a Self>>(iter: I) -> Self {
701         iter.fold(EnumSet::empty(), |a, v| a | *v)
702     }
703 }
704 impl <T: EnumSetType> Sum<T> for EnumSet<T> {
705     fn sum<I: Iterator<Item=T>>(iter: I) -> Self {
706         iter.fold(EnumSet::empty(), |a, v| a | v)
707     }
708 }
709 impl <'a, T: EnumSetType> Sum<&'a T> for EnumSet<T> {
710     fn sum<I: Iterator<Item=&'a T>>(iter: I) -> Self {
711         iter.fold(EnumSet::empty(), |a, v| a | *v)
712     }
713 }
714
715 impl <T: EnumSetType, O: Into<EnumSet<T>>> Sub<O> for EnumSet<T> {
716     type Output = Self;
717     #[inline(always)]
718     fn sub(self, other: O) -> Self::Output {
719         self.difference(other.into())
720     }
721 }
722 impl <T: EnumSetType, O: Into<EnumSet<T>>> BitAnd<O> for EnumSet<T> {
723     type Output = Self;
724     #[inline(always)]
725     fn bitand(self, other: O) -> Self::Output {
726         self.intersection(other.into())
727     }
728 }
729 impl <T: EnumSetType, O: Into<EnumSet<T>>> BitOr<O> for EnumSet<T> {
730     type Output = Self;
731     #[inline(always)]
732     fn bitor(self, other: O) -> Self::Output {
733         self.union(other.into())
734     }
735 }
736 impl <T: EnumSetType, O: Into<EnumSet<T>>> BitXor<O> for EnumSet<T> {
737     type Output = Self;
738     #[inline(always)]
739     fn bitxor(self, other: O) -> Self::Output {
740         self.symmetrical_difference(other.into())
741     }
742 }
743
744 impl <T: EnumSetType, O: Into<EnumSet<T>>> SubAssign<O> for EnumSet<T> {
745     #[inline(always)]
746     fn sub_assign(&mut self, rhs: O) {
747         *self = *self - rhs;
748     }
749 }
750 impl <T: EnumSetType, O: Into<EnumSet<T>>> BitAndAssign<O> for EnumSet<T> {
751     #[inline(always)]
752     fn bitand_assign(&mut self, rhs: O) {
753         *self = *self & rhs;
754     }
755 }
756 impl <T: EnumSetType, O: Into<EnumSet<T>>> BitOrAssign<O> for EnumSet<T> {
757     #[inline(always)]
758     fn bitor_assign(&mut self, rhs: O) {
759         *self = *self | rhs;
760     }
761 }
762 impl <T: EnumSetType, O: Into<EnumSet<T>>> BitXorAssign<O> for EnumSet<T> {
763     #[inline(always)]
764     fn bitxor_assign(&mut self, rhs: O) {
765         *self = *self ^ rhs;
766     }
767 }
768
769 impl <T: EnumSetType> Not for EnumSet<T> {
770     type Output = Self;
771     #[inline(always)]
772     fn not(self) -> Self::Output {
773         self.complement()
774     }
775 }
776
777 impl <T: EnumSetType> From<T> for EnumSet<T> {
778     fn from(t: T) -> Self {
779         EnumSet::only(t)
780     }
781 }
782
783 impl <T: EnumSetType> PartialEq<T> for EnumSet<T> {
784     fn eq(&self, other: &T) -> bool {
785         self.__priv_repr == EnumSet::only(*other).__priv_repr
786     }
787 }
788 impl <T: EnumSetType + Debug> Debug for EnumSet<T> {
789     fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
790         let mut is_first = true;
791         f.write_str("EnumSet(")?;
792         for v in self.iter() {
793             if !is_first { f.write_str(" | ")?; }
794             is_first = false;
795             v.fmt(f)?;
796         }
797         f.write_str(")")?;
798         Ok(())
799     }
800 }
801
802 #[allow(clippy::derive_hash_xor_eq)] // This impl exists to change trait bounds only.
803 impl <T: EnumSetType> Hash for EnumSet<T> {
804     fn hash<H: Hasher>(&self, state: &mut H) {
805         self.__priv_repr.hash(state)
806     }
807 }
808 impl <T: EnumSetType> PartialOrd for EnumSet<T> {
809     fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
810         self.__priv_repr.partial_cmp(&other.__priv_repr)
811     }
812 }
813 impl <T: EnumSetType> Ord for EnumSet<T> {
814     fn cmp(&self, other: &Self) -> Ordering {
815         self.__priv_repr.cmp(&other.__priv_repr)
816     }
817 }
818
819 #[cfg(feature = "serde")]
820 impl <T: EnumSetType> Serialize for EnumSet<T> {
821     fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
822         T::serialize(*self, serializer)
823     }
824 }
825
826 #[cfg(feature = "serde")]
827 impl <'de, T: EnumSetType> Deserialize<'de> for EnumSet<T> {
828     fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
829         T::deserialize(deserializer)
830     }
831 }
832
833 /// The iterator used by [`EnumSet`]s.
834 #[derive(Clone, Debug)]
835 pub struct EnumSetIter<T: EnumSetType> {
836     set: EnumSet<T>,
837 }
838 impl <T: EnumSetType> EnumSetIter<T> {
839     fn new(set: EnumSet<T>) -> EnumSetIter<T> {
840         EnumSetIter { set }
841     }
842 }
843
844 impl <T: EnumSetType> Iterator for EnumSetIter<T> {
845     type Item = T;
846
847     fn next(&mut self) -> Option<Self::Item> {
848         if self.set.is_empty() {
849             None
850         } else {
851             let bit = self.set.__priv_repr.trailing_zeros();
852             self.set.__priv_repr.remove_bit(bit);
853             unsafe { Some(T::enum_from_u32(bit)) }
854         }
855     }
856     fn size_hint(&self) -> (usize, Option<usize>) {
857         let left = self.set.len();
858         (left, Some(left))
859     }
860 }
861
862 impl <T: EnumSetType> DoubleEndedIterator for EnumSetIter<T> {
863     fn next_back(&mut self) -> Option<Self::Item> {
864         if self.set.is_empty() {
865             None
866         } else {
867             let bit = T::Repr::WIDTH - 1 - self.set.__priv_repr.leading_zeros();
868             self.set.__priv_repr.remove_bit(bit);
869             unsafe { Some(T::enum_from_u32(bit)) }
870         }
871     }
872 }
873
874 impl<T: EnumSetType> ExactSizeIterator for EnumSetIter<T> {}
875
876 impl<T: EnumSetType> Extend<T> for EnumSet<T> {
877     fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I) {
878         iter.into_iter().for_each(|v| { self.insert(v); });
879     }
880 }
881
882 impl<T: EnumSetType> FromIterator<T> for EnumSet<T> {
883     fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self {
884         let mut set = EnumSet::default();
885         set.extend(iter);
886         set
887     }
888 }
889
890 impl<T: EnumSetType> Extend<EnumSet<T>> for EnumSet<T> {
891     fn extend<I: IntoIterator<Item = EnumSet<T>>>(&mut self, iter: I) {
892         iter.into_iter().for_each(|v| { self.insert_all(v); });
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 }