]> git.lizzy.rs Git - enumset.git/blob - enumset/src/lib.rs
3be1cf064e097b471e1d1cdab01b752173c27ae7
[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 //! # Working with EnumSets
22 //!
23 //! EnumSets can be constructed via [`EnumSet::new()`] like a normal set. In addition,
24 //! `#[derive(EnumSetType)]` creates operator overloads that allow you to create EnumSets like so:
25 //!
26 //! ```rust
27 //! # use enumset::*;
28 //! # #[derive(EnumSetType, Debug)] pub enum Enum { A, B, C, D, E, F, G }
29 //! let new_set = Enum::A | Enum::C | Enum::G;
30 //! assert_eq!(new_set.len(), 3);
31 //! ```
32 //!
33 //! All bitwise operations you would expect to work on bitsets also work on both EnumSets and
34 //! enums with `#[derive(EnumSetType)]`:
35 //! ```rust
36 //! # use enumset::*;
37 //! # #[derive(EnumSetType, Debug)] pub enum Enum { A, B, C, D, E, F, G }
38 //! // Intersection of sets
39 //! assert_eq!((Enum::A | Enum::B) & Enum::C, EnumSet::empty());
40 //! assert_eq!((Enum::A | Enum::B) & Enum::A, Enum::A);
41 //! assert_eq!(Enum::A & Enum::B, EnumSet::empty());
42 //!
43 //! // Symmetric difference of sets
44 //! assert_eq!((Enum::A | Enum::B) ^ (Enum::B | Enum::C), Enum::A | Enum::C);
45 //! assert_eq!(Enum::A ^ Enum::C, Enum::A | Enum::C);
46 //!
47 //! // Difference of sets
48 //! assert_eq!((Enum::A | Enum::B | Enum::C) - Enum::B, Enum::A | Enum::C);
49 //!
50 //! // Complement of sets
51 //! assert_eq!(!(Enum::E | Enum::G), Enum::A | Enum::B | Enum::C | Enum::D | Enum::F);
52 //! ```
53 //!
54 //! The [`enum_set!`] macro allows you to create EnumSets in constant contexts:
55 //!
56 //! ```rust
57 //! # use enumset::*;
58 //! # #[derive(EnumSetType, Debug)] pub enum Enum { A, B, C, D, E, F, G }
59 //! const CONST_SET: EnumSet<Enum> = enum_set!(Enum::A | Enum::B);
60 //! assert_eq!(CONST_SET, Enum::A | Enum::B);
61 //! ```
62 //!
63 //! Mutable operations on the [`EnumSet`] otherwise work basically as expected:
64 //!
65 //! ```rust
66 //! # use enumset::*;
67 //! # #[derive(EnumSetType, Debug)] pub enum Enum { A, B, C, D, E, F, G }
68 //! let mut set = EnumSet::new();
69 //! set.insert(Enum::A);
70 //! set.insert_all(Enum::E | Enum::G);
71 //! assert!(set.contains(Enum::A));
72 //! assert!(!set.contains(Enum::B));
73 //! assert_eq!(set, Enum::A | Enum::E | Enum::G);
74 //! ```
75
76 pub use enumset_derive::*;
77
78 use core::cmp::Ordering;
79 use core::fmt;
80 use core::fmt::{Debug, Formatter};
81 use core::hash::{Hash, Hasher};
82 use core::iter::FromIterator;
83 use core::ops::*;
84
85 use num_traits::*;
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 struct used to type check [`enum_set!`].
93     pub struct EnumSetSameTypeHack<'a, T: EnumSetType + 'static> {
94         pub unified: &'a [T],
95         pub enum_set: EnumSet<T>,
96     }
97
98     /// A reexport of core to allow our macros to be generic to std vs core.
99     pub use ::core as core_export;
100
101     /// A reexport of serde so there is no requirement to depend on serde.
102     #[cfg(feature = "serde")] pub use serde2 as serde;
103
104     /// The actual members of EnumSetType. Put here to avoid polluting global namespaces.
105     pub unsafe trait EnumSetTypePrivate {
106         type Repr: EnumSetTypeRepr;
107         const ALL_BITS: Self::Repr;
108         fn enum_into_u8(self) -> u8;
109         unsafe fn enum_from_u8(val: u8) -> Self;
110
111         #[cfg(feature = "serde")]
112         fn serialize<S: serde::Serializer>(set: EnumSet<Self>, ser: S) -> Result<S::Ok, S::Error>
113             where Self: EnumSetType;
114         #[cfg(feature = "serde")]
115         fn deserialize<'de, D: serde::Deserializer<'de>>(de: D) -> Result<EnumSet<Self>, D::Error>
116             where Self: EnumSetType;
117     }
118 }
119 use crate::internal::EnumSetTypePrivate;
120 #[cfg(feature = "serde")] use crate::internal::serde;
121 #[cfg(feature = "serde")] use crate::serde::{Serialize, Deserialize};
122
123 mod private {
124     use super::*;
125     pub trait EnumSetTypeRepr : PrimInt + FromPrimitive + WrappingSub + CheckedShl + Debug + Hash {
126         const WIDTH: u8;
127     }
128     macro_rules! prim {
129         ($name:ty, $width:expr) => {
130             impl EnumSetTypeRepr for $name {
131                 const WIDTH: u8 = $width;
132             }
133         }
134     }
135     prim!(u8  , 8  );
136     prim!(u16 , 16 );
137     prim!(u32 , 32 );
138     prim!(u64 , 64 );
139     prim!(u128, 128);
140 }
141 use crate::private::EnumSetTypeRepr;
142
143 /// The trait used to define enum types that may be used with [`EnumSet`].
144 ///
145 /// This trait should be implemented using `#[derive(EnumSetType)]`. Its internal structure is
146 /// not currently stable, and may change at any time.
147 ///
148 /// # Custom Derive
149 ///
150 /// The custom derive for [`EnumSetType`] automatically creates implementations of [`PartialEq`],
151 /// [`Sub`], [`BitAnd`], [`BitOr`], [`BitXor`], and [`Not`] allowing the enum to be used as
152 /// if it were an [`EnumSet`] in expressions. This can be disabled by adding an `#[enumset(no_ops)]`
153 /// annotation to the enum.
154 ///
155 /// The custom derive for `EnumSetType` automatically implements [`Copy`], [`Clone`], [`Eq`], and
156 /// [`PartialEq`] on the enum. These are required for the [`EnumSet`] to function.
157 ///
158 /// Any C-like enum is supported, as long as there are no more than 128 variants in the enum,
159 /// and no variant discriminator is larger than 127.
160 ///
161 /// # Examples
162 ///
163 /// Deriving a plain EnumSetType:
164 ///
165 /// ```rust
166 /// # use enumset::*;
167 /// #[derive(EnumSetType)]
168 /// pub enum Enum {
169 ///    A, B, C, D, E, F, G,
170 /// }
171 /// ```
172 ///
173 /// Deriving a sparse EnumSetType:
174 ///
175 /// ```rust
176 /// # use enumset::*;
177 /// #[derive(EnumSetType)]
178 /// pub enum SparseEnum {
179 ///    A = 10, B = 20, C = 30, D = 127,
180 /// }
181 /// ```
182 ///
183 /// Deriving an EnumSetType without adding ops:
184 ///
185 /// ```rust
186 /// # use enumset::*;
187 /// #[derive(EnumSetType)]
188 /// #[enumset(no_ops)]
189 /// pub enum NoOpsEnum {
190 ///    A, B, C, D, E, F, G,
191 /// }
192 /// ```
193 pub unsafe trait EnumSetType: Copy + Eq + EnumSetTypePrivate { }
194
195 /// An efficient set type for enums.
196 ///
197 /// # Serialization
198 ///
199 /// The default representation serializes enumsets as an `u8`, `u16`, `u32`, `u64`, or `u128`,
200 /// whichever is the smallest that can contain all bits that are part of the set.
201 ///
202 /// Unknown bits are ignored, and are simply dropped. To override this behavior, you can add a
203 /// `#[enumset(serialize_deny_unknown)]` annotation to your enum.
204 ///
205 /// You can add a `#[enumset(serialize_repr = "u8")]` annotation to your enum to explicitly set
206 /// the bit width the `EnumSet` is serialized as. This can be used to avoid breaking changes in
207 /// certain serialization formats (such as `bincode`).
208 ///
209 /// In addition, the `#[enumset(serialize_as_list)]` annotation causes the `EnumSet` to be
210 /// instead serialized as a list. This requires your enum type implement [`Serialize`] and
211 /// [`Deserialize`].
212 #[derive(Copy, Clone, PartialEq, Eq)]
213 pub struct EnumSet<T : EnumSetType> {
214     #[doc(hidden)]
215     /// This is public due to the [`enum_set!`] macro.
216     /// This is **NOT** public API and may change at any time.
217     pub __enumset_underlying: T::Repr
218 }
219 impl <T : EnumSetType> EnumSet<T> {
220     fn mask(bit: u8) -> T::Repr {
221         Shl::<usize>::shl(T::Repr::one(), bit as usize)
222     }
223     fn has_bit(&self, bit: u8) -> bool {
224         let mask = Self::mask(bit);
225         self.__enumset_underlying & mask == mask
226     }
227     fn partial_bits(bits: u8) -> T::Repr {
228         T::Repr::one().checked_shl(bits.into())
229             .unwrap_or(T::Repr::zero())
230             .wrapping_sub(&T::Repr::one())
231     }
232
233     // Returns all bits valid for the enum
234     fn all_bits() -> T::Repr {
235         T::ALL_BITS
236     }
237
238     /// Returns an empty set.
239     pub fn new() -> Self {
240         EnumSet { __enumset_underlying: T::Repr::zero() }
241     }
242
243     /// Returns a set containing a single value.
244     pub fn only(t: T) -> Self {
245         EnumSet { __enumset_underlying: Self::mask(t.enum_into_u8()) }
246     }
247
248     /// Returns an empty set.
249     pub fn empty() -> Self {
250         Self::new()
251     }
252     /// Returns a set with all bits set.
253     pub fn all() -> Self {
254         EnumSet { __enumset_underlying: Self::all_bits() }
255     }
256
257     /// Total number of bits this enumset uses. Note that the actual amount of space used is
258     /// rounded up to the next highest integer type (`u8`, `u16`, `u32`, `u64`, or `u128`).
259     ///
260     /// This is the same as [`EnumSet::variant_count`] except in enums with "sparse" variants.
261     /// (e.g. `enum Foo { A = 10, B = 20 }`)
262     pub fn bit_width() -> u8 {
263         T::Repr::WIDTH - T::ALL_BITS.leading_zeros() as u8
264     }
265
266     /// The number of valid variants in this enumset.
267     ///
268     /// This is the same as [`EnumSet::bit_width`] except in enums with "sparse" variants.
269     /// (e.g. `enum Foo { A = 10, B = 20 }`)
270     pub fn variant_count() -> u8 {
271         T::ALL_BITS.count_ones() as u8
272     }
273
274     /// Returns the raw bits of this set
275     pub fn to_bits(&self) -> u128 {
276         self.__enumset_underlying.to_u128()
277             .expect("Impossible: Bits cannot be to converted into i128?")
278     }
279
280     /// Constructs a bitset from raw bits.
281     ///
282     /// # Panics
283     /// If bits not in the enum are set.
284     pub fn from_bits(bits: u128) -> Self {
285         assert!((bits & !Self::all().to_bits()) == 0, "Bits not valid for the enum were set.");
286         EnumSet {
287             __enumset_underlying: T::Repr::from_u128(bits)
288                 .expect("Impossible: Valid bits too large to fit in repr?")
289         }
290     }
291
292     /// Returns the number of values in this set.
293     pub fn len(&self) -> usize {
294         self.__enumset_underlying.count_ones() as usize
295     }
296     /// Checks if the set is empty.
297     pub fn is_empty(&self) -> bool {
298         self.__enumset_underlying.is_zero()
299     }
300     /// Removes all elements from the set.
301     pub fn clear(&mut self) {
302         self.__enumset_underlying = T::Repr::zero()
303     }
304
305     /// Checks if this set shares no elements with another.
306     pub fn is_disjoint(&self, other: Self) -> bool {
307         (*self & other).is_empty()
308     }
309     /// Checks if all elements in another set are in this set.
310     pub fn is_superset(&self, other: Self) -> bool {
311         (*self & other).__enumset_underlying == other.__enumset_underlying
312     }
313     /// Checks if all elements of this set are in another set.
314     pub fn is_subset(&self, other: Self) -> bool {
315         other.is_superset(*self)
316     }
317
318     /// Returns a set containing the union of all elements in both sets.
319     pub fn union(&self, other: Self) -> Self {
320         EnumSet { __enumset_underlying: self.__enumset_underlying | other.__enumset_underlying }
321     }
322     /// Returns a set containing all elements in common with another set.
323     pub fn intersection(&self, other: Self) -> Self {
324         EnumSet { __enumset_underlying: self.__enumset_underlying & other.__enumset_underlying }
325     }
326     /// Returns a set with all elements of the other set removed.
327     pub fn difference(&self, other: Self) -> Self {
328         EnumSet { __enumset_underlying: self.__enumset_underlying & !other.__enumset_underlying }
329     }
330     /// Returns a set with all elements not contained in both sets.
331     pub fn symmetrical_difference(&self, other: Self) -> Self {
332         EnumSet { __enumset_underlying: self.__enumset_underlying ^ other.__enumset_underlying }
333     }
334     /// Returns a set containing all elements not in this set.
335     pub fn complement(&self) -> Self {
336         EnumSet { __enumset_underlying: !self.__enumset_underlying & Self::all_bits() }
337     }
338
339     /// Checks whether this set contains a value.
340     pub fn contains(&self, value: T) -> bool {
341         self.has_bit(value.enum_into_u8())
342     }
343
344     /// Adds a value to this set.
345     pub fn insert(&mut self, value: T) -> bool {
346         let contains = self.contains(value);
347         self.__enumset_underlying = self.__enumset_underlying | Self::mask(value.enum_into_u8());
348         contains
349     }
350     /// Removes a value from this set.
351     pub fn remove(&mut self, value: T) -> bool {
352         let contains = self.contains(value);
353         self.__enumset_underlying = self.__enumset_underlying & !Self::mask(value.enum_into_u8());
354         contains
355     }
356
357     /// Adds all elements in another set to this one.
358     pub fn insert_all(&mut self, other: Self) {
359         self.__enumset_underlying = self.__enumset_underlying | other.__enumset_underlying
360     }
361     /// Removes all values in another set from this one.
362     pub fn remove_all(&mut self, other: Self) {
363         self.__enumset_underlying = self.__enumset_underlying & !other.__enumset_underlying
364     }
365
366     /// Creates an iterator over the values in this set.
367     pub fn iter(&self) -> EnumSetIter<T> {
368         EnumSetIter(*self, 0)
369     }
370 }
371
372 impl <T: EnumSetType> Default for EnumSet<T> {
373     /// Returns an empty set.
374     fn default() -> Self {
375         Self::new()
376     }
377 }
378
379 impl <T : EnumSetType> IntoIterator for EnumSet<T> {
380     type Item = T;
381     type IntoIter = EnumSetIter<T>;
382
383     fn into_iter(self) -> Self::IntoIter {
384         self.iter()
385     }
386 }
387
388 impl <T : EnumSetType, O: Into<EnumSet<T>>> Sub<O> for EnumSet<T> {
389     type Output = Self;
390     fn sub(self, other: O) -> Self::Output {
391         self.difference(other.into())
392     }
393 }
394 impl <T : EnumSetType, O: Into<EnumSet<T>>> BitAnd<O> for EnumSet<T> {
395     type Output = Self;
396     fn bitand(self, other: O) -> Self::Output {
397         self.intersection(other.into())
398     }
399 }
400 impl <T : EnumSetType, O: Into<EnumSet<T>>> BitOr<O> for EnumSet<T> {
401     type Output = Self;
402     fn bitor(self, other: O) -> Self::Output {
403         self.union(other.into())
404     }
405 }
406 impl <T : EnumSetType, O: Into<EnumSet<T>>> BitXor<O> for EnumSet<T> {
407     type Output = Self;
408     fn bitxor(self, other: O) -> Self::Output {
409         self.symmetrical_difference(other.into())
410     }
411 }
412
413 impl <T : EnumSetType, O: Into<EnumSet<T>>> SubAssign<O> for EnumSet<T> {
414     fn sub_assign(&mut self, rhs: O) {
415         *self = *self - rhs;
416     }
417 }
418 impl <T : EnumSetType, O: Into<EnumSet<T>>> BitAndAssign<O> for EnumSet<T> {
419     fn bitand_assign(&mut self, rhs: O) {
420         *self = *self & rhs;
421     }
422 }
423 impl <T : EnumSetType, O: Into<EnumSet<T>>> BitOrAssign<O> for EnumSet<T> {
424     fn bitor_assign(&mut self, rhs: O) {
425         *self = *self | rhs;
426     }
427 }
428 impl <T : EnumSetType, O: Into<EnumSet<T>>> BitXorAssign<O> for EnumSet<T> {
429     fn bitxor_assign(&mut self, rhs: O) {
430         *self = *self ^ rhs;
431     }
432 }
433
434 impl <T : EnumSetType> Not for EnumSet<T> {
435     type Output = Self;
436     fn not(self) -> Self::Output {
437         self.complement()
438     }
439 }
440
441 impl <T : EnumSetType> From<T> for EnumSet<T> {
442     fn from(t: T) -> Self {
443         EnumSet::only(t)
444     }
445 }
446
447 impl <T : EnumSetType> PartialEq<T> for EnumSet<T> {
448     fn eq(&self, other: &T) -> bool {
449         self.__enumset_underlying == EnumSet::<T>::mask(other.enum_into_u8())
450     }
451 }
452 impl <T : EnumSetType + Debug> Debug for EnumSet<T> {
453     fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
454         let mut is_first = true;
455         f.write_str("EnumSet(")?;
456         for v in self.iter() {
457             if !is_first { f.write_str(" | ")?; }
458             is_first = false;
459             v.fmt(f)?;
460         }
461         f.write_str(")")?;
462         Ok(())
463     }
464 }
465
466 impl <T: EnumSetType> Hash for EnumSet<T> {
467     fn hash<H: Hasher>(&self, state: &mut H) {
468         self.__enumset_underlying.hash(state)
469     }
470 }
471 impl <T: EnumSetType> PartialOrd for EnumSet<T> {
472     fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
473         self.__enumset_underlying.partial_cmp(&other.__enumset_underlying)
474     }
475 }
476 impl <T: EnumSetType> Ord for EnumSet<T> {
477     fn cmp(&self, other: &Self) -> Ordering {
478         self.__enumset_underlying.cmp(&other.__enumset_underlying)
479     }
480 }
481
482 #[cfg(feature = "serde")]
483 impl <T : EnumSetType> Serialize for EnumSet<T> {
484     fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
485         T::serialize(*self, serializer)
486     }
487 }
488
489 #[cfg(feature = "serde")]
490 impl <'de, T : EnumSetType> Deserialize<'de> for EnumSet<T> {
491     fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
492         T::deserialize(deserializer)
493     }
494 }
495
496 /// The iterator used by [`EnumSet`](./struct.EnumSet.html).
497 #[derive(Copy, Clone, PartialOrd, Ord, PartialEq, Eq, Hash, Debug)]
498 pub struct EnumSetIter<T : EnumSetType>(EnumSet<T>, u8);
499 impl <T : EnumSetType> Iterator for EnumSetIter<T> {
500     type Item = T;
501
502     fn next(&mut self) -> Option<Self::Item> {
503         while self.1 < EnumSet::<T>::bit_width() {
504             let bit = self.1;
505             self.1 += 1;
506             if self.0.has_bit(bit) {
507                 return unsafe { Some(T::enum_from_u8(bit)) }
508             }
509         }
510         None
511     }
512     fn size_hint(&self) -> (usize, Option<usize>) {
513         let left_mask = !EnumSet::<T>::partial_bits(self.1);
514         let left = (self.0.__enumset_underlying & left_mask).count_ones() as usize;
515         (left, Some(left))
516     }
517 }
518
519 impl<T: EnumSetType> Extend<T> for EnumSet<T> {
520     fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I) {
521         iter.into_iter().for_each(|v| { self.insert(v); });
522     }
523 }
524
525 impl<T: EnumSetType> FromIterator<T> for EnumSet<T> {
526     fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self {
527         let mut set = EnumSet::default();
528         set.extend(iter);
529         set
530     }
531 }
532
533 /// Creates a EnumSet literal, which can be used in const contexts.
534 ///
535 /// The syntax used is `enum_set!(Type::A | Type::B | Type::C)`. Each variant must be of the same
536 /// type, or a error will occur at compile-time.
537 ///
538 /// # Examples
539 ///
540 /// ```rust
541 /// # use enumset::*;
542 /// # #[derive(EnumSetType, Debug)] enum Enum { A, B, C }
543 /// const CONST_SET: EnumSet<Enum> = enum_set!(Enum::A | Enum::B);
544 /// assert_eq!(CONST_SET, Enum::A | Enum::B);
545 /// ```
546 ///
547 /// This macro is strongly typed. For example, the following will not compile:
548 ///
549 /// ```compile_fail
550 /// # use enumset::*;
551 /// # #[derive(EnumSetType, Debug)] enum Enum { A, B, C }
552 /// # #[derive(EnumSetType, Debug)] enum Enum2 { A, B, C }
553 /// let type_error = enum_set!(Enum::A | Enum2::B);
554 /// ```
555 #[macro_export]
556 macro_rules! enum_set {
557     () => {
558         $crate::EnumSet { __enumset_underlying: 0 }
559     };
560     ($($value:path)|* $(|)*) => {
561         $crate::internal::EnumSetSameTypeHack {
562             unified: &[$($value,)*],
563             enum_set: $crate::EnumSet {
564                 __enumset_underlying: 0 $(| (1 << ($value as u8)))*
565             },
566         }.enum_set
567     };
568 }