]> git.lizzy.rs Git - enumset.git/blob - enumset/src/lib.rs
Remove dependency on num_traits.
[enumset.git] / enumset / src / lib.rs
1 #![no_std]
2 #![forbid(missing_docs)]
3
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.
6 //!
7 //! For serde support, enable the `serde` feature.
8 //!
9 //! # Defining enums for use with EnumSet
10 //!
11 //! Enums to be used with [`EnumSet`] should be defined using `#[derive(EnumSetType)]`:
12 //!
13 //! ```rust
14 //! # use enumset::*;
15 //! #[derive(EnumSetType, Debug)]
16 //! pub enum Enum {
17 //!    A, B, C, D, E, F, G,
18 //! }
19 //! ```
20 //!
21 //! For more information on more advanced use cases, see the documentation for [`EnumSetType`].
22 //!
23 //! # Working with EnumSets
24 //!
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:
27 //!
28 //! ```rust
29 //! # use enumset::*;
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);
33 //! ```
34 //!
35 //! All bitwise operations you would expect to work on bitsets also work on both EnumSets and
36 //! enums with `#[derive(EnumSetType)]`:
37 //! ```rust
38 //! # use enumset::*;
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());
44 //!
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);
48 //!
49 //! // Difference of sets
50 //! assert_eq!((Enum::A | Enum::B | Enum::C) - Enum::B, Enum::A | Enum::C);
51 //!
52 //! // Complement of sets
53 //! assert_eq!(!(Enum::E | Enum::G), Enum::A | Enum::B | Enum::C | Enum::D | Enum::F);
54 //! ```
55 //!
56 //! The [`enum_set!`] macro allows you to create EnumSets in constant contexts:
57 //!
58 //! ```rust
59 //! # use enumset::*;
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);
63 //! ```
64 //!
65 //! Mutable operations on the [`EnumSet`] otherwise similarly to Rust's builtin sets:
66 //!
67 //! ```rust
68 //! # use enumset::*;
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);
76 //! ```
77
78 pub use enumset_derive::EnumSetType;
79
80 use core::cmp::Ordering;
81 use core::fmt;
82 use core::fmt::{Debug, Formatter};
83 use core::hash::{Hash, Hasher};
84 use core::iter::FromIterator;
85 use core::ops::*;
86
87 #[doc(hidden)]
88 /// Everything in this module is internal API and may change at any time.
89 pub mod __internal {
90     use super::*;
91
92     /// A reexport of core to allow our macros to be generic to std vs core.
93     pub use ::core as core_export;
94
95     /// A reexport of serde so there is no requirement to depend on serde.
96     #[cfg(feature = "serde")] pub use serde2 as serde;
97
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;
104
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;
109
110         /// Serializes the `EnumSet`.
111         ///
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;
121     }
122 }
123 use crate::__internal::EnumSetTypePrivate;
124 #[cfg(feature = "serde")] use crate::__internal::serde;
125 #[cfg(feature = "serde")] use crate::serde::{Serialize, Deserialize};
126
127 mod private {
128     use super::*;
129     use core::convert::TryInto;
130
131     /// A trait marking valid underlying bitset storage types and providing the
132     /// operations `EnumSet` and related types use.
133     pub trait EnumSetTypeRepr :
134         // Basic traits used to derive traits
135         Copy +
136         Ord +
137         Eq +
138         Debug +
139         Hash +
140         // Operations used by enumset
141         BitAnd<Output = Self> +
142         BitOr<Output = Self> +
143         BitXor<Output = Self> +
144         Not<Output = Self> +
145     {
146         const WIDTH: u32;
147
148         fn is_empty(&self) -> bool;
149         fn empty() -> Self;
150
151         fn add_bit(&mut self, bit: u32);
152         fn remove_bit(&mut self, bit: u32);
153         fn has_bit(&self, bit: u32) -> bool;
154
155         fn count_ones(&self) -> u32;
156         fn count_remaining_ones(&self, cursor: u32) -> usize;
157         fn leading_zeros(&self) -> u32;
158
159         fn from_u8(v: u8) -> Self;
160         fn from_u16(v: u16) -> Self;
161         fn from_u32(v: u32) -> Self;
162         fn from_u64(v: u64) -> Self;
163         fn from_u128(v: u128) -> Self;
164         fn from_usize(v: usize) -> Self;
165
166         fn to_u8(&self) -> u8;
167         fn to_u16(&self) -> u16;
168         fn to_u32(&self) -> u32;
169         fn to_u64(&self) -> u64;
170         fn to_u128(&self) -> u128;
171         fn to_usize(&self) -> usize;
172
173         fn from_u8_opt(v: u8) -> Option<Self>;
174         fn from_u16_opt(v: u16) -> Option<Self>;
175         fn from_u32_opt(v: u32) -> Option<Self>;
176         fn from_u64_opt(v: u64) -> Option<Self>;
177         fn from_u128_opt(v: u128) -> Option<Self>;
178         fn from_usize_opt(v: usize) -> Option<Self>;
179
180         fn to_u8_opt(&self) -> Option<u8>;
181         fn to_u16_opt(&self) -> Option<u16>;
182         fn to_u32_opt(&self) -> Option<u32>;
183         fn to_u64_opt(&self) -> Option<u64>;
184         fn to_u128_opt(&self) -> Option<u128>;
185         fn to_usize_opt(&self) -> Option<usize>;
186     }
187     macro_rules! prim {
188         ($name:ty, $width:expr) => {
189             impl EnumSetTypeRepr for $name {
190                 const WIDTH: u32 = $width;
191
192                 fn is_empty(&self) -> bool { *self == 0 }
193                 fn empty() -> Self { 0 }
194
195                 fn add_bit(&mut self, bit: u32) {
196                     *self |= 1 << bit as $name;
197                 }
198                 fn remove_bit(&mut self, bit: u32) {
199                     *self &= !(1 << bit as $name);
200                 }
201                 fn has_bit(&self, bit: u32) -> bool {
202                     (self & (1 << bit as $name)) != 0
203                 }
204
205                 fn count_ones(&self) -> u32 { (*self).count_ones() }
206                 fn leading_zeros(&self) -> u32 { (*self).leading_zeros() }
207
208                 fn count_remaining_ones(&self, cursor: u32) -> usize {
209                     let left_mask =
210                         !((1 as $name).checked_shl(cursor).unwrap_or(0).wrapping_sub(1));
211                     (*self & left_mask).count_ones() as usize
212                 }
213
214                 fn from_u8(v: u8) -> Self { v as $name }
215                 fn from_u16(v: u16) -> Self { v as $name }
216                 fn from_u32(v: u32) -> Self { v as $name }
217                 fn from_u64(v: u64) -> Self { v as $name }
218                 fn from_u128(v: u128) -> Self { v as $name }
219                 fn from_usize(v: usize) -> Self { v as $name }
220
221                 fn to_u8(&self) -> u8 { (*self) as u8 }
222                 fn to_u16(&self) -> u16 { (*self) as u16 }
223                 fn to_u32(&self) -> u32 { (*self) as u32 }
224                 fn to_u64(&self) -> u64 { (*self) as u64 }
225                 fn to_u128(&self) -> u128 { (*self) as u128 }
226                 fn to_usize(&self) -> usize { (*self) as usize }
227
228                 fn from_u8_opt(v: u8) -> Option<Self> { v.try_into().ok() }
229                 fn from_u16_opt(v: u16) -> Option<Self> { v.try_into().ok() }
230                 fn from_u32_opt(v: u32) -> Option<Self> { v.try_into().ok() }
231                 fn from_u64_opt(v: u64) -> Option<Self> { v.try_into().ok() }
232                 fn from_u128_opt(v: u128) -> Option<Self> { v.try_into().ok() }
233                 fn from_usize_opt(v: usize) -> Option<Self> { v.try_into().ok() }
234
235                 fn to_u8_opt(&self) -> Option<u8> { (*self).try_into().ok() }
236                 fn to_u16_opt(&self) -> Option<u16> { (*self).try_into().ok() }
237                 fn to_u32_opt(&self) -> Option<u32> { (*self).try_into().ok() }
238                 fn to_u64_opt(&self) -> Option<u64> { (*self).try_into().ok() }
239                 fn to_u128_opt(&self) -> Option<u128> { (*self).try_into().ok() }
240                 fn to_usize_opt(&self) -> Option<usize> { (*self).try_into().ok() }
241             }
242         }
243     }
244     prim!(u8  , 8  );
245     prim!(u16 , 16 );
246     prim!(u32 , 32 );
247     prim!(u64 , 64 );
248     prim!(u128, 128);
249 }
250 use crate::private::EnumSetTypeRepr;
251
252 /// The trait used to define enum types that may be used with [`EnumSet`].
253 ///
254 /// This trait should be implemented using `#[derive(EnumSetType)]`. Its internal structure is
255 /// not stable, and may change at any time.
256 ///
257 /// # Custom Derive
258 ///
259 /// Any C-like enum is supported, as long as there are no more than 128 variants in the enum,
260 /// and no variant discriminator is larger than 127.
261 ///
262 /// The custom derive for [`EnumSetType`] automatically creates implementations of [`PartialEq`],
263 /// [`Sub`], [`BitAnd`], [`BitOr`], [`BitXor`], and [`Not`] allowing the enum to be used as
264 /// if it were an [`EnumSet`] in expressions. This can be disabled by adding an `#[enumset(no_ops)]`
265 /// annotation to the enum.
266 ///
267 /// The custom derive for `EnumSetType` automatically implements [`Copy`], [`Clone`], [`Eq`], and
268 /// [`PartialEq`] on the enum. These are required for the [`EnumSet`] to function.
269 ///
270 /// In addition, if you have renamed the `enumset` crate in your crate, you can use the
271 /// `#[enumset(crate_name = "enumset2")]` attribute to tell the custom derive to use that name
272 /// instead.
273 ///
274 /// Attributes controlling the serialization of an `EnumSet` are documented in
275 /// [its documentation](./struct.EnumSet.html#serialization).
276 ///
277 /// # Examples
278 ///
279 /// Deriving a plain EnumSetType:
280 ///
281 /// ```rust
282 /// # use enumset::*;
283 /// #[derive(EnumSetType)]
284 /// pub enum Enum {
285 ///    A, B, C, D, E, F, G,
286 /// }
287 /// ```
288 ///
289 /// Deriving a sparse EnumSetType:
290 ///
291 /// ```rust
292 /// # use enumset::*;
293 /// #[derive(EnumSetType)]
294 /// pub enum SparseEnum {
295 ///    A = 10, B = 20, C = 30, D = 127,
296 /// }
297 /// ```
298 ///
299 /// Deriving an EnumSetType without adding ops:
300 ///
301 /// ```rust
302 /// # use enumset::*;
303 /// #[derive(EnumSetType)]
304 /// #[enumset(no_ops)]
305 /// pub enum NoOpsEnum {
306 ///    A, B, C, D, E, F, G,
307 /// }
308 /// ```
309 pub unsafe trait EnumSetType: Copy + Eq + EnumSetTypePrivate { }
310
311 /// An efficient set type for enums.
312 ///
313 /// It is implemented using a bitset stored using the smallest integer that can fit all bits
314 /// in the underlying enum. In general, an enum variant with a numeric value of `n` is stored in
315 /// the nth least significant bit (corresponding with a mask of, e.g. `1 << enum as u32`).
316 ///
317 /// # Serialization
318 ///
319 /// When the `serde` feature is enabled, `EnumSet`s can be serialized and deserialized using
320 /// the `serde` crate. The exact serialization format can be controlled with additional attributes
321 /// on the enum type. These attributes are valid regardless of whether the `serde` feature
322 /// is enabled.
323 ///
324 /// By default, `EnumSet`s serialize by directly writing out the underlying bitset as an integer
325 /// of the smallest type that can fit in the underlying enum. You can add a
326 /// `#[enumset(serialize_repr = "u8")]` attribute to your enum to control the integer type used
327 /// for serialization. This can be important for avoiding unintentional breaking changes when
328 /// `EnumSet`s are serialized with formats like `bincode`.
329 ///
330 /// By default, unknown bits are ignored and silently removed from the bitset. To override this
331 /// behavior, you can add a `#[enumset(serialize_deny_unknown)]` attribute. This will cause
332 /// deserialization to fail if an invalid bit is set.
333 ///
334 /// In addition, the `#[enumset(serialize_as_list)]` attribute causes the `EnumSet` to be
335 /// instead serialized as a list of enum variants. This requires your enum type implement
336 /// [`Serialize`] and [`Deserialize`]. Note that this is a breaking change
337 #[derive(Copy, Clone, PartialEq, Eq)]
338 pub struct EnumSet<T: EnumSetType> {
339     #[doc(hidden)]
340     /// This is public due to the [`enum_set!`] macro.
341     /// This is **NOT** public API and may change at any time.
342     pub __enumset_underlying: T::Repr
343 }
344 impl <T: EnumSetType> EnumSet<T> {
345     // Returns all bits valid for the enum
346     fn all_bits() -> T::Repr {
347         T::ALL_BITS
348     }
349
350     /// Creates an empty `EnumSet`.
351     pub fn new() -> Self {
352         EnumSet { __enumset_underlying: T::Repr::empty() }
353     }
354
355     /// Returns an `EnumSet` containing a single element.
356     pub fn only(t: T) -> Self {
357         let mut set = Self::new();
358         set.insert(t);
359         set
360     }
361
362     /// Creates an empty `EnumSet`.
363     ///
364     /// This is an alias for [`EnumSet::new`].
365     pub fn empty() -> Self {
366         Self::new()
367     }
368
369     /// Returns an `EnumSet` containing all valid variants of the enum.
370     pub fn all() -> Self {
371         EnumSet { __enumset_underlying: Self::all_bits() }
372     }
373
374     /// Total number of bits used by this type. Note that the actual amount of space used is
375     /// rounded up to the next highest integer type (`u8`, `u16`, `u32`, `u64`, or `u128`).
376     ///
377     /// This is the same as [`EnumSet::variant_count`] except in enums with "sparse" variants.
378     /// (e.g. `enum Foo { A = 10, B = 20 }`)
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     pub fn variant_count() -> u32 {
388         T::ALL_BITS.count_ones()
389     }
390
391     /// Returns the number of elements in this set.
392     pub fn len(&self) -> usize {
393         self.__enumset_underlying.count_ones() as usize
394     }
395     /// Returns `true` if the set contains no elements.
396     pub fn is_empty(&self) -> bool {
397         self.__enumset_underlying.is_empty()
398     }
399     /// Removes all elements from the set.
400     pub fn clear(&mut self) {
401         self.__enumset_underlying = 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     pub fn is_disjoint(&self, other: Self) -> bool {
407         (*self & other).is_empty()
408     }
409     /// Returns `true` if the set is a superset of another, i.e., `self` contains at least all the
410     /// values in `other`.
411     pub fn is_superset(&self, other: Self) -> bool {
412         (*self & other).__enumset_underlying == other.__enumset_underlying
413     }
414     /// Returns `true` if the set is a subset of another, i.e., `other` contains at least all
415     /// the values in `self`.
416     pub fn is_subset(&self, other: Self) -> bool {
417         other.is_superset(*self)
418     }
419
420     /// Returns a set containing any elements present in either set.
421     pub fn union(&self, other: Self) -> Self {
422         EnumSet { __enumset_underlying: self.__enumset_underlying | other.__enumset_underlying }
423     }
424     /// Returns a set containing every element present in both sets.
425     pub fn intersection(&self, other: Self) -> Self {
426         EnumSet { __enumset_underlying: self.__enumset_underlying & other.__enumset_underlying }
427     }
428     /// Returns a set containing element present in `self` but not in `other`.
429     pub fn difference(&self, other: Self) -> Self {
430         EnumSet { __enumset_underlying: self.__enumset_underlying & !other.__enumset_underlying }
431     }
432     /// Returns a set containing every element present in either `self` or `other`, but is not
433     /// present in both.
434     pub fn symmetrical_difference(&self, other: Self) -> Self {
435         EnumSet { __enumset_underlying: self.__enumset_underlying ^ other.__enumset_underlying }
436     }
437     /// Returns a set containing all enum variants not in this set.
438     pub fn complement(&self) -> Self {
439         EnumSet { __enumset_underlying: !self.__enumset_underlying & Self::all_bits() }
440     }
441
442     /// Checks whether this set contains a value.
443     pub fn contains(&self, value: T) -> bool {
444         self.__enumset_underlying.has_bit(value.enum_into_u32())
445     }
446
447     /// Adds a value to this set.
448     ///
449     /// If the set did not have this value present, `true` is returned.
450     ///
451     /// If the set did have this value present, `false` is returned.
452     pub fn insert(&mut self, value: T) -> bool {
453         let contains = !self.contains(value);
454         self.__enumset_underlying.add_bit(value.enum_into_u32());
455         contains
456     }
457     /// Removes a value from this set. Returns whether the value was present in the set.
458     pub fn remove(&mut self, value: T) -> bool {
459         let contains = self.contains(value);
460         self.__enumset_underlying.remove_bit(value.enum_into_u32());
461         contains
462     }
463
464     /// Adds all elements in another set to this one.
465     pub fn insert_all(&mut self, other: Self) {
466         self.__enumset_underlying = self.__enumset_underlying | other.__enumset_underlying
467     }
468     /// Removes all values in another set from this one.
469     pub fn remove_all(&mut self, other: Self) {
470         self.__enumset_underlying = self.__enumset_underlying & !other.__enumset_underlying
471     }
472
473     /// Creates an iterator over the values in this set.
474     ///
475     /// Note that iterator invalidation is impossible as the iterator contains a copy of this type,
476     /// rather than holding a reference to it.
477     pub fn iter(&self) -> EnumSetIter<T> {
478         EnumSetIter(*self, 0)
479     }
480 }
481
482 /// Helper macro for generating conversion functions.
483 macro_rules! conversion_impls {
484     (
485         $(for_num!(
486             $underlying:ty, $underlying_str:expr,
487             $from_fn:ident $to_fn:ident $from_fn_opt:ident $to_fn_opt:ident,
488             $from:ident $try_from:ident $from_truncated:ident
489             $to:ident $try_to:ident $to_truncated:ident
490         );)*
491     ) => {
492         impl <T : EnumSetType> EnumSet<T> {$(
493             #[doc = "Returns a `"]
494             #[doc = $underlying_str]
495             #[doc = "` representing the elements of this set.\n\nIf the underlying bitset will \
496                      not fit in a `"]
497             #[doc = $underlying_str]
498             #[doc = "`, this method will panic."]
499             pub fn $to(&self) -> $underlying {
500                 self.$try_to().expect("Bitset will not fit into this type.")
501             }
502
503             #[doc = "Tries to return a `"]
504             #[doc = $underlying_str]
505             #[doc = "` representing the elements of this set.\n\nIf the underlying bitset will \
506                      not fit in a `"]
507             #[doc = $underlying_str]
508             #[doc = "`, this method will instead return `None`."]
509             pub fn $try_to(&self) -> Option<$underlying> {
510                 EnumSetTypeRepr::$to_fn_opt(&self.__enumset_underlying)
511             }
512
513             #[doc = "Returns a truncated `"]
514             #[doc = $underlying_str]
515             #[doc = "` representing the elements of this set.\n\nIf the underlying bitset will \
516                      not fit in a `"]
517             #[doc = $underlying_str]
518             #[doc = "`, this method will truncate any bits that don't fit."]
519             pub fn $to_truncated(&self) -> $underlying {
520                 EnumSetTypeRepr::$to_fn(&self.__enumset_underlying)
521             }
522
523             #[doc = "Constructs a bitset from a `"]
524             #[doc = $underlying_str]
525             #[doc = "`.\n\nIf a bit that doesn't correspond to an enum variant is set, this \
526                      method will panic."]
527             pub fn $from(bits: $underlying) -> Self {
528                 Self::$try_from(bits).expect("Bitset contains invalid variants.")
529             }
530
531             #[doc = "Attempts to constructs a bitset from a `"]
532             #[doc = $underlying_str]
533             #[doc = "`.\n\nIf a bit that doesn't correspond to an enum variant is set, this \
534                      method will return `None`."]
535             pub fn $try_from(bits: $underlying) -> Option<Self> {
536                 let bits = T::Repr::$from_fn_opt(bits);
537                 let mask = Self::all().__enumset_underlying;
538                 bits.and_then(|bits| if (bits & !mask).is_empty() {
539                     Some(EnumSet { __enumset_underlying: bits })
540                 } else {
541                     None
542                 })
543             }
544
545             #[doc = "Constructs a bitset from a `"]
546             #[doc = $underlying_str]
547             #[doc = "`, ignoring invalid variants."]
548             pub fn $from_truncated(bits: $underlying) -> Self {
549                 let mask = Self::all().$to_truncated();
550                 let bits = <T::Repr as EnumSetTypeRepr>::$from_fn(bits & mask);
551                 EnumSet { __enumset_underlying: bits }
552             }
553         )*}
554     }
555 }
556 conversion_impls! {
557     for_num!(u8, "u8", from_u8 to_u8 from_u8_opt to_u8_opt,
558              from_u8 try_from_u8 from_u8_truncated as_u8 try_as_u8 as_u8_truncated);
559     for_num!(u16, "u16", from_u16 to_u16 from_u16_opt to_u16_opt,
560              from_u16 try_from_u16 from_u16_truncated as_u16 try_as_u16 as_u16_truncated);
561     for_num!(u32, "u32", from_u32 to_u32 from_u32_opt to_u32_opt,
562              from_u32 try_from_u32 from_u32_truncated as_u32 try_as_u32 as_u32_truncated);
563     for_num!(u64, "u64", from_u64 to_u64 from_u64_opt to_u64_opt,
564              from_u64 try_from_u64 from_u64_truncated as_u64 try_as_u64 as_u64_truncated);
565     for_num!(u128, "u128", from_u128 to_u128 from_u128_opt to_u128_opt,
566              from_u128 try_from_u128 from_u128_truncated as_u128 try_as_u128 as_u128_truncated);
567     for_num!(usize, "usize", from_usize to_usize from_usize_opt to_usize_opt,
568              from_usize try_from_usize from_usize_truncated
569              as_usize try_as_usize as_usize_truncated);
570 }
571
572 impl <T: EnumSetType> Default for EnumSet<T> {
573     /// Returns an empty set.
574     fn default() -> Self {
575         Self::new()
576     }
577 }
578
579 impl <T: EnumSetType> IntoIterator for EnumSet<T> {
580     type Item = T;
581     type IntoIter = EnumSetIter<T>;
582
583     fn into_iter(self) -> Self::IntoIter {
584         self.iter()
585     }
586 }
587
588 impl <T: EnumSetType, O: Into<EnumSet<T>>> Sub<O> for EnumSet<T> {
589     type Output = Self;
590     fn sub(self, other: O) -> Self::Output {
591         self.difference(other.into())
592     }
593 }
594 impl <T: EnumSetType, O: Into<EnumSet<T>>> BitAnd<O> for EnumSet<T> {
595     type Output = Self;
596     fn bitand(self, other: O) -> Self::Output {
597         self.intersection(other.into())
598     }
599 }
600 impl <T: EnumSetType, O: Into<EnumSet<T>>> BitOr<O> for EnumSet<T> {
601     type Output = Self;
602     fn bitor(self, other: O) -> Self::Output {
603         self.union(other.into())
604     }
605 }
606 impl <T: EnumSetType, O: Into<EnumSet<T>>> BitXor<O> for EnumSet<T> {
607     type Output = Self;
608     fn bitxor(self, other: O) -> Self::Output {
609         self.symmetrical_difference(other.into())
610     }
611 }
612
613 impl <T: EnumSetType, O: Into<EnumSet<T>>> SubAssign<O> for EnumSet<T> {
614     fn sub_assign(&mut self, rhs: O) {
615         *self = *self - rhs;
616     }
617 }
618 impl <T: EnumSetType, O: Into<EnumSet<T>>> BitAndAssign<O> for EnumSet<T> {
619     fn bitand_assign(&mut self, rhs: O) {
620         *self = *self & rhs;
621     }
622 }
623 impl <T: EnumSetType, O: Into<EnumSet<T>>> BitOrAssign<O> for EnumSet<T> {
624     fn bitor_assign(&mut self, rhs: O) {
625         *self = *self | rhs;
626     }
627 }
628 impl <T: EnumSetType, O: Into<EnumSet<T>>> BitXorAssign<O> for EnumSet<T> {
629     fn bitxor_assign(&mut self, rhs: O) {
630         *self = *self ^ rhs;
631     }
632 }
633
634 impl <T: EnumSetType> Not for EnumSet<T> {
635     type Output = Self;
636     fn not(self) -> Self::Output {
637         self.complement()
638     }
639 }
640
641 impl <T: EnumSetType> From<T> for EnumSet<T> {
642     fn from(t: T) -> Self {
643         EnumSet::only(t)
644     }
645 }
646
647 impl <T: EnumSetType> PartialEq<T> for EnumSet<T> {
648     fn eq(&self, other: &T) -> bool {
649         self.__enumset_underlying == EnumSet::only(*other).__enumset_underlying
650     }
651 }
652 impl <T: EnumSetType + Debug> Debug for EnumSet<T> {
653     fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
654         let mut is_first = true;
655         f.write_str("EnumSet(")?;
656         for v in self.iter() {
657             if !is_first { f.write_str(" | ")?; }
658             is_first = false;
659             v.fmt(f)?;
660         }
661         f.write_str(")")?;
662         Ok(())
663     }
664 }
665
666 impl <T: EnumSetType> Hash for EnumSet<T> {
667     fn hash<H: Hasher>(&self, state: &mut H) {
668         self.__enumset_underlying.hash(state)
669     }
670 }
671 impl <T: EnumSetType> PartialOrd for EnumSet<T> {
672     fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
673         self.__enumset_underlying.partial_cmp(&other.__enumset_underlying)
674     }
675 }
676 impl <T: EnumSetType> Ord for EnumSet<T> {
677     fn cmp(&self, other: &Self) -> Ordering {
678         self.__enumset_underlying.cmp(&other.__enumset_underlying)
679     }
680 }
681
682 #[cfg(feature = "serde")]
683 impl <T: EnumSetType> Serialize for EnumSet<T> {
684     fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
685         T::serialize(*self, serializer)
686     }
687 }
688
689 #[cfg(feature = "serde")]
690 impl <'de, T: EnumSetType> Deserialize<'de> for EnumSet<T> {
691     fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
692         T::deserialize(deserializer)
693     }
694 }
695
696 /// The iterator used by [`EnumSet`]s.
697 #[derive(Clone, Debug)]
698 pub struct EnumSetIter<T: EnumSetType>(EnumSet<T>, u32);
699 impl <T: EnumSetType> Iterator for EnumSetIter<T> {
700     type Item = T;
701
702     fn next(&mut self) -> Option<Self::Item> {
703         while self.1 < EnumSet::<T>::bit_width() {
704             let bit = self.1;
705             self.1 += 1;
706             if self.0.__enumset_underlying.has_bit(bit) {
707                 return unsafe { Some(T::enum_from_u32(bit)) }
708             }
709         }
710         None
711     }
712     fn size_hint(&self) -> (usize, Option<usize>) {
713         let left = self.0.__enumset_underlying.count_remaining_ones(self.1);
714         (left, Some(left))
715     }
716 }
717
718 impl<T: EnumSetType> Extend<T> for EnumSet<T> {
719     fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I) {
720         iter.into_iter().for_each(|v| { self.insert(v); });
721     }
722 }
723
724 impl<T: EnumSetType> FromIterator<T> for EnumSet<T> {
725     fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self {
726         let mut set = EnumSet::default();
727         set.extend(iter);
728         set
729     }
730 }
731
732 impl<T: EnumSetType> Extend<EnumSet<T>> for EnumSet<T> {
733     fn extend<I: IntoIterator<Item = EnumSet<T>>>(&mut self, iter: I) {
734         iter.into_iter().for_each(|v| { self.insert_all(v); });
735     }
736 }
737
738 impl<T: EnumSetType> FromIterator<EnumSet<T>> for EnumSet<T> {
739     fn from_iter<I: IntoIterator<Item = EnumSet<T>>>(iter: I) -> Self {
740         let mut set = EnumSet::default();
741         set.extend(iter);
742         set
743     }
744 }
745
746 /// Creates a EnumSet literal, which can be used in const contexts.
747 ///
748 /// The syntax used is `enum_set!(Type::A | Type::B | Type::C)`. Each variant must be of the same
749 /// type, or a error will occur at compile-time.
750 ///
751 /// This macro accepts trailing `|`s to allow easier use in other macros.
752 ///
753 /// # Examples
754 ///
755 /// ```rust
756 /// # use enumset::*;
757 /// # #[derive(EnumSetType, Debug)] enum Enum { A, B, C }
758 /// const CONST_SET: EnumSet<Enum> = enum_set!(Enum::A | Enum::B);
759 /// assert_eq!(CONST_SET, Enum::A | Enum::B);
760 /// ```
761 ///
762 /// This macro is strongly typed. For example, the following will not compile:
763 ///
764 /// ```compile_fail
765 /// # use enumset::*;
766 /// # #[derive(EnumSetType, Debug)] enum Enum { A, B, C }
767 /// # #[derive(EnumSetType, Debug)] enum Enum2 { A, B, C }
768 /// let type_error = enum_set!(Enum::A | Enum2::B);
769 /// ```
770 #[macro_export]
771 macro_rules! enum_set {
772     ($(|)*) => {
773         $crate::EnumSet { __enumset_underlying: 0 }
774     };
775     ($value:path $(|)*) => {
776         $value.__impl_enumset_internal__const_only()
777     };
778     ($value:path | $($rest:path)|* $(|)*) => {
779         {
780             #[allow(deprecated)] let value = $value.__impl_enumset_internal__const_only();
781             $(#[allow(deprecated)] let value = $rest.__impl_enumset_internal__const_merge(value);)*
782             value
783         }
784     };
785 }