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