#![no_std]
#![forbid(missing_docs)]
pub use enumset_derive::*;
use core::cmp::Ordering;
use core::fmt;
use core::fmt::{Debug, Formatter};
use core::hash::{Hash, Hasher};
use core::iter::FromIterator;
use core::ops::*;
use num_traits::*;
#[doc(hidden)]
pub mod internal {
use super::*;
pub struct EnumSetSameTypeHack<'a, T: EnumSetType + 'static> {
pub unified: &'a [T],
pub enum_set: EnumSet<T>,
}
pub use ::core as core_export;
#[cfg(feature = "serde")] pub use serde2 as serde;
pub unsafe trait EnumSetTypePrivate {
type Repr: EnumSetTypeRepr;
const ALL_BITS: Self::Repr;
fn enum_into_u8(self) -> u8;
unsafe fn enum_from_u8(val: u8) -> Self;
#[cfg(feature = "serde")]
fn serialize<S: serde::Serializer>(set: EnumSet<Self>, ser: S) -> Result<S::Ok, S::Error>
where Self: EnumSetType;
#[cfg(feature = "serde")]
fn deserialize<'de, D: serde::Deserializer<'de>>(de: D) -> Result<EnumSet<Self>, D::Error>
where Self: EnumSetType;
}
}
use crate::internal::EnumSetTypePrivate;
#[cfg(feature = "serde")] use crate::internal::serde;
#[cfg(feature = "serde")] use crate::serde::{Serialize, Deserialize};
mod private {
use super::*;
pub trait EnumSetTypeRepr : PrimInt + FromPrimitive + WrappingSub + CheckedShl + Debug + Hash {
const WIDTH: u8;
}
macro_rules! prim {
($name:ty, $width:expr) => {
impl EnumSetTypeRepr for $name {
const WIDTH: u8 = $width;
}
}
}
prim!(u8 , 8 );
prim!(u16 , 16 );
prim!(u32 , 32 );
prim!(u64 , 64 );
prim!(u128, 128);
}
use crate::private::EnumSetTypeRepr;
pub unsafe trait EnumSetType: Copy + Eq + EnumSetTypePrivate { }
#[derive(Copy, Clone, PartialEq, Eq)]
pub struct EnumSet<T : EnumSetType> {
#[doc(hidden)]
pub __enumset_underlying: T::Repr
}
impl <T : EnumSetType> EnumSet<T> {
fn mask(bit: u8) -> T::Repr {
Shl::<usize>::shl(T::Repr::one(), bit as usize)
}
fn has_bit(&self, bit: u8) -> bool {
let mask = Self::mask(bit);
self.__enumset_underlying & mask == mask
}
fn partial_bits(bits: u8) -> T::Repr {
T::Repr::one().checked_shl(bits.into())
.unwrap_or(T::Repr::zero())
.wrapping_sub(&T::Repr::one())
}
fn all_bits() -> T::Repr {
T::ALL_BITS
}
pub fn new() -> Self {
EnumSet { __enumset_underlying: T::Repr::zero() }
}
pub fn only(t: T) -> Self {
EnumSet { __enumset_underlying: Self::mask(t.enum_into_u8()) }
}
pub fn empty() -> Self {
Self::new()
}
pub fn all() -> Self {
EnumSet { __enumset_underlying: Self::all_bits() }
}
pub fn bit_width() -> u8 {
T::Repr::WIDTH - T::ALL_BITS.leading_zeros() as u8
}
pub fn variant_count() -> u8 {
T::ALL_BITS.count_ones() as u8
}
pub fn to_bits(&self) -> u128 {
self.__enumset_underlying.to_u128()
.expect("Impossible: Bits cannot be to converted into i128?")
}
pub fn from_bits(bits: u128) -> Self {
assert!((bits & !Self::all().to_bits()) == 0, "Bits not valid for the enum were set.");
EnumSet {
__enumset_underlying: T::Repr::from_u128(bits)
.expect("Impossible: Valid bits too large to fit in repr?")
}
}
pub fn len(&self) -> usize {
self.__enumset_underlying.count_ones() as usize
}
pub fn is_empty(&self) -> bool {
self.__enumset_underlying.is_zero()
}
pub fn clear(&mut self) {
self.__enumset_underlying = T::Repr::zero()
}
pub fn is_disjoint(&self, other: Self) -> bool {
(*self & other).is_empty()
}
pub fn is_superset(&self, other: Self) -> bool {
(*self & other).__enumset_underlying == other.__enumset_underlying
}
pub fn is_subset(&self, other: Self) -> bool {
other.is_superset(*self)
}
pub fn union(&self, other: Self) -> Self {
EnumSet { __enumset_underlying: self.__enumset_underlying | other.__enumset_underlying }
}
pub fn intersection(&self, other: Self) -> Self {
EnumSet { __enumset_underlying: self.__enumset_underlying & other.__enumset_underlying }
}
pub fn difference(&self, other: Self) -> Self {
EnumSet { __enumset_underlying: self.__enumset_underlying & !other.__enumset_underlying }
}
pub fn symmetrical_difference(&self, other: Self) -> Self {
EnumSet { __enumset_underlying: self.__enumset_underlying ^ other.__enumset_underlying }
}
pub fn complement(&self) -> Self {
EnumSet { __enumset_underlying: !self.__enumset_underlying & Self::all_bits() }
}
pub fn contains(&self, value: T) -> bool {
self.has_bit(value.enum_into_u8())
}
pub fn insert(&mut self, value: T) -> bool {
let contains = self.contains(value);
self.__enumset_underlying = self.__enumset_underlying | Self::mask(value.enum_into_u8());
contains
}
pub fn remove(&mut self, value: T) -> bool {
let contains = self.contains(value);
self.__enumset_underlying = self.__enumset_underlying & !Self::mask(value.enum_into_u8());
contains
}
pub fn insert_all(&mut self, other: Self) {
self.__enumset_underlying = self.__enumset_underlying | other.__enumset_underlying
}
pub fn remove_all(&mut self, other: Self) {
self.__enumset_underlying = self.__enumset_underlying & !other.__enumset_underlying
}
pub fn iter(&self) -> EnumSetIter<T> {
EnumSetIter(*self, 0)
}
}
impl <T: EnumSetType> Default for EnumSet<T> {
fn default() -> Self {
Self::new()
}
}
impl <T : EnumSetType> IntoIterator for EnumSet<T> {
type Item = T;
type IntoIter = EnumSetIter<T>;
fn into_iter(self) -> Self::IntoIter {
self.iter()
}
}
impl <T : EnumSetType, O: Into<EnumSet<T>>> Sub<O> for EnumSet<T> {
type Output = Self;
fn sub(self, other: O) -> Self::Output {
self.difference(other.into())
}
}
impl <T : EnumSetType, O: Into<EnumSet<T>>> BitAnd<O> for EnumSet<T> {
type Output = Self;
fn bitand(self, other: O) -> Self::Output {
self.intersection(other.into())
}
}
impl <T : EnumSetType, O: Into<EnumSet<T>>> BitOr<O> for EnumSet<T> {
type Output = Self;
fn bitor(self, other: O) -> Self::Output {
self.union(other.into())
}
}
impl <T : EnumSetType, O: Into<EnumSet<T>>> BitXor<O> for EnumSet<T> {
type Output = Self;
fn bitxor(self, other: O) -> Self::Output {
self.symmetrical_difference(other.into())
}
}
impl <T : EnumSetType, O: Into<EnumSet<T>>> SubAssign<O> for EnumSet<T> {
fn sub_assign(&mut self, rhs: O) {
*self = *self - rhs;
}
}
impl <T : EnumSetType, O: Into<EnumSet<T>>> BitAndAssign<O> for EnumSet<T> {
fn bitand_assign(&mut self, rhs: O) {
*self = *self & rhs;
}
}
impl <T : EnumSetType, O: Into<EnumSet<T>>> BitOrAssign<O> for EnumSet<T> {
fn bitor_assign(&mut self, rhs: O) {
*self = *self | rhs;
}
}
impl <T : EnumSetType, O: Into<EnumSet<T>>> BitXorAssign<O> for EnumSet<T> {
fn bitxor_assign(&mut self, rhs: O) {
*self = *self ^ rhs;
}
}
impl <T : EnumSetType> Not for EnumSet<T> {
type Output = Self;
fn not(self) -> Self::Output {
self.complement()
}
}
impl <T : EnumSetType> From<T> for EnumSet<T> {
fn from(t: T) -> Self {
EnumSet::only(t)
}
}
impl <T : EnumSetType> PartialEq<T> for EnumSet<T> {
fn eq(&self, other: &T) -> bool {
self.__enumset_underlying == EnumSet::<T>::mask(other.enum_into_u8())
}
}
impl <T : EnumSetType + Debug> Debug for EnumSet<T> {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
let mut is_first = true;
f.write_str("EnumSet(")?;
for v in self.iter() {
if !is_first { f.write_str(" | ")?; }
is_first = false;
v.fmt(f)?;
}
f.write_str(")")?;
Ok(())
}
}
impl <T: EnumSetType> Hash for EnumSet<T> {
fn hash<H: Hasher>(&self, state: &mut H) {
self.__enumset_underlying.hash(state)
}
}
impl <T: EnumSetType> PartialOrd for EnumSet<T> {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
self.__enumset_underlying.partial_cmp(&other.__enumset_underlying)
}
}
impl <T: EnumSetType> Ord for EnumSet<T> {
fn cmp(&self, other: &Self) -> Ordering {
self.__enumset_underlying.cmp(&other.__enumset_underlying)
}
}
#[cfg(feature = "serde")]
impl <T : EnumSetType> Serialize for EnumSet<T> {
fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
T::serialize(*self, serializer)
}
}
#[cfg(feature = "serde")]
impl <'de, T : EnumSetType> Deserialize<'de> for EnumSet<T> {
fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
T::deserialize(deserializer)
}
}
#[derive(Copy, Clone, PartialOrd, Ord, PartialEq, Eq, Hash, Debug)]
pub struct EnumSetIter<T : EnumSetType>(EnumSet<T>, u8);
impl <T : EnumSetType> Iterator for EnumSetIter<T> {
type Item = T;
fn next(&mut self) -> Option<Self::Item> {
while self.1 < EnumSet::<T>::bit_width() {
let bit = self.1;
self.1 += 1;
if self.0.has_bit(bit) {
return unsafe { Some(T::enum_from_u8(bit)) }
}
}
None
}
fn size_hint(&self) -> (usize, Option<usize>) {
let left_mask = !EnumSet::<T>::partial_bits(self.1);
let left = (self.0.__enumset_underlying & left_mask).count_ones() as usize;
(left, Some(left))
}
}
impl<T: EnumSetType> Extend<T> for EnumSet<T> {
fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I) {
iter.into_iter().for_each(|v| { self.insert(v); });
}
}
impl<T: EnumSetType> FromIterator<T> for EnumSet<T> {
fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self {
let mut set = EnumSet::default();
set.extend(iter);
set
}
}
#[macro_export]
macro_rules! enum_set {
() => {
$crate::EnumSet { __enumset_underlying: 0 }
};
($($value:path)|* $(|)*) => {
$crate::internal::EnumSetSameTypeHack {
unified: &[$($value,)*],
enum_set: $crate::EnumSet {
__enumset_underlying: 0 $(| (1 << ($value as u8)))*
},
}.enum_set
};
}