#![no_std]
#![forbid(missing_docs)]
-
// The safety requirement is "use the procedural derive".
#![allow(clippy::missing_safety_doc)]
pub use ::core as core_export;
/// A reexport of serde so there is no requirement to depend on serde.
- #[cfg(feature = "serde")] pub use serde2 as serde;
+ #[cfg(feature = "serde")]
+ pub use serde2 as serde;
/// The actual members of EnumSetType. Put here to avoid polluting global namespaces.
pub unsafe trait EnumSetTypePrivate {
/// can control how `EnumSet` is serialized.
#[cfg(feature = "serde")]
fn serialize<S: serde::Serializer>(set: EnumSet<Self>, ser: S) -> Result<S::Ok, S::Error>
- where Self: EnumSetType;
+ where Self: EnumSetType;
/// Deserializes the `EnumSet`.
#[cfg(feature = "serde")]
fn deserialize<'de, D: serde::Deserializer<'de>>(de: D) -> Result<EnumSet<Self>, D::Error>
- where Self: EnumSetType;
+ where Self: EnumSetType;
}
}
+#[cfg(feature = "serde")]
+use crate::__internal::serde;
use crate::__internal::EnumSetTypePrivate;
-#[cfg(feature = "serde")] use crate::__internal::serde;
-#[cfg(feature = "serde")] use crate::serde::{Serialize, Deserialize};
+#[cfg(feature = "serde")]
+use crate::serde::{Deserialize, Serialize};
mod repr;
use crate::repr::EnumSetTypeRepr;
///
/// For full documentation on the procedural derive and its options, see
/// [`#[derive(EnumSetType)]`](./derive.EnumSetType.html).
-pub unsafe trait EnumSetType: Copy + Eq + EnumSetTypePrivate { }
+pub unsafe trait EnumSetType: Copy + Eq + EnumSetTypePrivate {}
/// An [`EnumSetType`] for which [`EnumSet`]s have a guaranteed in-memory representation.
///
/// For any type `T` that implements this trait, the in-memory representation of `EnumSet<T>`
/// is guaranteed to be `Repr`. This guarantee is useful for FFI. See [the `EnumSet` documentation
/// under “FFI, Safety and `repr`”][EnumSet#ffi-safety-and-repr] for an example.
-pub unsafe trait EnumSetTypeWithRepr: EnumSetType + EnumSetTypePrivate<Repr = <Self as EnumSetTypeWithRepr>::Repr> {
+pub unsafe trait EnumSetTypeWithRepr:
+ EnumSetType + EnumSetTypePrivate<Repr = <Self as EnumSetTypeWithRepr>::Repr>
+{
/// The guaranteed representation.
type Repr: EnumSetTypeRepr;
}
///
/// # FFI, Safety and `repr`
///
-/// If an enum type `T` is annotated with [`#[enumset(repr = "R")]`][derive@EnumSetType#options], then
-/// several things happen:
+/// If an enum type `T` is annotated with [`#[enumset(repr = "R")]`][derive@EnumSetType#options],
+/// then several things happen:
///
/// * `T` will implement <code>[EnumSetTypeWithRepr]<Repr = R></code> in addition to
/// [`EnumSetType`].
#[doc(hidden)]
/// This is public due to the [`enum_set!`] macro.
/// This is **NOT** public API and may change at any time.
- pub __priv_repr: T::Repr
+ pub __priv_repr: T::Repr,
}
-impl <T: EnumSetType> EnumSet<T> {
+impl<T: EnumSetType> EnumSet<T> {
// Returns all bits valid for the enum
#[inline(always)]
fn all_bits() -> T::Repr {
/// annotation.
#[inline(always)]
pub fn as_repr(&self) -> <T as EnumSetTypeWithRepr>::Repr
- where
- T: EnumSetTypeWithRepr,
- {
+ where T: EnumSetTypeWithRepr {
self.__priv_repr
}
/// `T` must be set to 0. Behavior is **undefined** if any of these bits are set to 1.
#[inline(always)]
pub unsafe fn from_repr_unchecked(bits: <T as EnumSetTypeWithRepr>::Repr) -> Self
- where
- T: EnumSetTypeWithRepr,
- {
+ where T: EnumSetTypeWithRepr {
Self { __priv_repr: bits }
}
/// annotation.
#[inline(always)]
pub fn from_repr(bits: <T as EnumSetTypeWithRepr>::Repr) -> Self
- where
- T: EnumSetTypeWithRepr,
- {
+ where T: EnumSetTypeWithRepr {
Self::try_from_repr(bits).expect("Bitset contains invalid variants.")
}
/// annotation.
#[inline(always)]
pub fn try_from_repr(bits: <T as EnumSetTypeWithRepr>::Repr) -> Option<Self>
- where
- T: EnumSetTypeWithRepr,
- {
+ where T: EnumSetTypeWithRepr {
let mask = Self::all().__priv_repr;
if bits.and_not(mask).is_empty() {
Some(EnumSet { __priv_repr: bits })
/// annotation.
#[inline(always)]
pub fn from_repr_truncated(bits: <T as EnumSetTypeWithRepr>::Repr) -> Self
- where
- T: EnumSetTypeWithRepr,
- {
+ where T: EnumSetTypeWithRepr {
let mask = Self::all().as_repr();
let bits = bits & mask;
EnumSet { __priv_repr: bits }
as_usize try_as_usize as_usize_truncated);
}
-impl <T: EnumSetType> Default for EnumSet<T> {
+impl<T: EnumSetType> Default for EnumSet<T> {
/// Returns an empty set.
fn default() -> Self {
Self::new()
}
}
-impl <T: EnumSetType> IntoIterator for EnumSet<T> {
+impl<T: EnumSetType> IntoIterator for EnumSet<T> {
type Item = T;
type IntoIter = EnumSetIter<T>;
self.iter()
}
}
-impl <T: EnumSetType> Sum for EnumSet<T> {
- fn sum<I: Iterator<Item=Self>>(iter: I) -> Self {
+impl<T: EnumSetType> Sum for EnumSet<T> {
+ fn sum<I: Iterator<Item = Self>>(iter: I) -> Self {
iter.fold(EnumSet::empty(), |a, v| a | v)
}
}
-impl <'a, T: EnumSetType> Sum<&'a EnumSet<T>> for EnumSet<T> {
- fn sum<I: Iterator<Item=&'a Self>>(iter: I) -> Self {
+impl<'a, T: EnumSetType> Sum<&'a EnumSet<T>> for EnumSet<T> {
+ fn sum<I: Iterator<Item = &'a Self>>(iter: I) -> Self {
iter.fold(EnumSet::empty(), |a, v| a | *v)
}
}
-impl <T: EnumSetType> Sum<T> for EnumSet<T> {
- fn sum<I: Iterator<Item=T>>(iter: I) -> Self {
+impl<T: EnumSetType> Sum<T> for EnumSet<T> {
+ fn sum<I: Iterator<Item = T>>(iter: I) -> Self {
iter.fold(EnumSet::empty(), |a, v| a | v)
}
}
-impl <'a, T: EnumSetType> Sum<&'a T> for EnumSet<T> {
- fn sum<I: Iterator<Item=&'a T>>(iter: I) -> Self {
+impl<'a, T: EnumSetType> Sum<&'a T> for EnumSet<T> {
+ fn sum<I: Iterator<Item = &'a T>>(iter: I) -> Self {
iter.fold(EnumSet::empty(), |a, v| a | *v)
}
}
-impl <T: EnumSetType, O: Into<EnumSet<T>>> Sub<O> for EnumSet<T> {
+impl<T: EnumSetType, O: Into<EnumSet<T>>> Sub<O> for EnumSet<T> {
type Output = Self;
#[inline(always)]
fn sub(self, other: O) -> Self::Output {
self.difference(other.into())
}
}
-impl <T: EnumSetType, O: Into<EnumSet<T>>> BitAnd<O> for EnumSet<T> {
+impl<T: EnumSetType, O: Into<EnumSet<T>>> BitAnd<O> for EnumSet<T> {
type Output = Self;
#[inline(always)]
fn bitand(self, other: O) -> Self::Output {
self.intersection(other.into())
}
}
-impl <T: EnumSetType, O: Into<EnumSet<T>>> BitOr<O> for EnumSet<T> {
+impl<T: EnumSetType, O: Into<EnumSet<T>>> BitOr<O> for EnumSet<T> {
type Output = Self;
#[inline(always)]
fn bitor(self, other: O) -> Self::Output {
self.union(other.into())
}
}
-impl <T: EnumSetType, O: Into<EnumSet<T>>> BitXor<O> for EnumSet<T> {
+impl<T: EnumSetType, O: Into<EnumSet<T>>> BitXor<O> for EnumSet<T> {
type Output = Self;
#[inline(always)]
fn bitxor(self, other: O) -> Self::Output {
}
}
-impl <T: EnumSetType, O: Into<EnumSet<T>>> SubAssign<O> for EnumSet<T> {
+impl<T: EnumSetType, O: Into<EnumSet<T>>> SubAssign<O> for EnumSet<T> {
#[inline(always)]
fn sub_assign(&mut self, rhs: O) {
*self = *self - rhs;
}
}
-impl <T: EnumSetType, O: Into<EnumSet<T>>> BitAndAssign<O> for EnumSet<T> {
+impl<T: EnumSetType, O: Into<EnumSet<T>>> BitAndAssign<O> for EnumSet<T> {
#[inline(always)]
fn bitand_assign(&mut self, rhs: O) {
*self = *self & rhs;
}
}
-impl <T: EnumSetType, O: Into<EnumSet<T>>> BitOrAssign<O> for EnumSet<T> {
+impl<T: EnumSetType, O: Into<EnumSet<T>>> BitOrAssign<O> for EnumSet<T> {
#[inline(always)]
fn bitor_assign(&mut self, rhs: O) {
*self = *self | rhs;
}
}
-impl <T: EnumSetType, O: Into<EnumSet<T>>> BitXorAssign<O> for EnumSet<T> {
+impl<T: EnumSetType, O: Into<EnumSet<T>>> BitXorAssign<O> for EnumSet<T> {
#[inline(always)]
fn bitxor_assign(&mut self, rhs: O) {
*self = *self ^ rhs;
}
}
-impl <T: EnumSetType> Not for EnumSet<T> {
+impl<T: EnumSetType> Not for EnumSet<T> {
type Output = Self;
#[inline(always)]
fn not(self) -> Self::Output {
}
}
-impl <T: EnumSetType> From<T> for EnumSet<T> {
+impl<T: EnumSetType> From<T> for EnumSet<T> {
fn from(t: T) -> Self {
EnumSet::only(t)
}
}
-impl <T: EnumSetType> PartialEq<T> for EnumSet<T> {
+impl<T: EnumSetType> PartialEq<T> for EnumSet<T> {
fn eq(&self, other: &T) -> bool {
self.__priv_repr == EnumSet::only(*other).__priv_repr
}
}
-impl <T: EnumSetType + Debug> Debug for EnumSet<T> {
+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(" | ")?; }
+ if !is_first {
+ f.write_str(" | ")?;
+ }
is_first = false;
v.fmt(f)?;
}
}
#[allow(clippy::derive_hash_xor_eq)] // This impl exists to change trait bounds only.
-impl <T: EnumSetType> Hash for EnumSet<T> {
+impl<T: EnumSetType> Hash for EnumSet<T> {
fn hash<H: Hasher>(&self, state: &mut H) {
self.__priv_repr.hash(state)
}
}
-impl <T: EnumSetType> PartialOrd for EnumSet<T> {
+impl<T: EnumSetType> PartialOrd for EnumSet<T> {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
self.__priv_repr.partial_cmp(&other.__priv_repr)
}
}
-impl <T: EnumSetType> Ord for EnumSet<T> {
+impl<T: EnumSetType> Ord for EnumSet<T> {
fn cmp(&self, other: &Self) -> Ordering {
self.__priv_repr.cmp(&other.__priv_repr)
}
}
#[cfg(feature = "serde")]
-impl <T: EnumSetType> Serialize for EnumSet<T> {
+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> {
+impl<'de, T: EnumSetType> Deserialize<'de> for EnumSet<T> {
fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
T::deserialize(deserializer)
}
pub struct EnumSetIter<T: EnumSetType> {
set: EnumSet<T>,
}
-impl <T: EnumSetType> EnumSetIter<T> {
+impl<T: EnumSetType> EnumSetIter<T> {
fn new(set: EnumSet<T>) -> EnumSetIter<T> {
EnumSetIter { set }
}
}
-impl <T: EnumSetType> Iterator for EnumSetIter<T> {
+impl<T: EnumSetType> Iterator for EnumSetIter<T> {
type Item = T;
fn next(&mut self) -> Option<Self::Item> {
}
}
-impl <T: EnumSetType> DoubleEndedIterator for EnumSetIter<T> {
+impl<T: EnumSetType> DoubleEndedIterator for EnumSetIter<T> {
fn next_back(&mut self) -> Option<Self::Item> {
if self.set.is_empty() {
None
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); });
+ iter.into_iter().for_each(|v| {
+ self.insert(v);
+ });
}
}
impl<T: EnumSetType> Extend<EnumSet<T>> for EnumSet<T> {
fn extend<I: IntoIterator<Item = EnumSet<T>>>(&mut self, iter: I) {
- iter.into_iter().for_each(|v| { self.insert_all(v); });
+ iter.into_iter().for_each(|v| {
+ self.insert_all(v);
+ });
}
}
use core::convert::TryInto;
-use core::fmt::{Debug};
-use core::hash::{Hash};
+use core::fmt::Debug;
+use core::hash::Hash;
use core::ops::*;
/// A trait marking valid underlying bitset storage types and providing the
const WIDTH: u32 = $width;
#[inline(always)]
- fn is_empty(&self) -> bool { *self == 0 }
+ fn is_empty(&self) -> bool {
+ *self == 0
+ }
#[inline(always)]
- fn empty() -> Self { 0 }
+ fn empty() -> Self {
+ 0
+ }
#[inline(always)]
fn add_bit(&mut self, bit: u32) {
}
#[inline(always)]
- fn count_ones(&self) -> u32 { (*self).count_ones() }
+ fn count_ones(&self) -> u32 {
+ (*self).count_ones()
+ }
#[inline(always)]
- fn leading_zeros(&self) -> u32 { (*self).leading_zeros() }
+ fn leading_zeros(&self) -> u32 {
+ (*self).leading_zeros()
+ }
#[inline(always)]
- fn trailing_zeros(&self) -> u32 { (*self).trailing_zeros() }
+ fn trailing_zeros(&self) -> u32 {
+ (*self).trailing_zeros()
+ }
#[inline(always)]
- fn and_not(&self, other: Self) -> Self { (*self) & !other }
+ fn and_not(&self, other: Self) -> Self {
+ (*self) & !other
+ }
#[inline(always)]
fn count_remaining_ones(&self, cursor: u32) -> usize {
- let left_mask =
- !((1 as $name).checked_shl(cursor).unwrap_or(0).wrapping_sub(1));
+ let left_mask = !((1 as $name)
+ .checked_shl(cursor)
+ .unwrap_or(0)
+ .wrapping_sub(1));
(*self & left_mask).count_ones() as usize
}
#[inline(always)]
- fn from_u8(v: u8) -> Self { v as $name }
+ fn from_u8(v: u8) -> Self {
+ v as $name
+ }
#[inline(always)]
- fn from_u16(v: u16) -> Self { v as $name }
+ fn from_u16(v: u16) -> Self {
+ v as $name
+ }
#[inline(always)]
- fn from_u32(v: u32) -> Self { v as $name }
+ fn from_u32(v: u32) -> Self {
+ v as $name
+ }
#[inline(always)]
- fn from_u64(v: u64) -> Self { v as $name }
+ fn from_u64(v: u64) -> Self {
+ v as $name
+ }
#[inline(always)]
- fn from_u128(v: u128) -> Self { v as $name }
+ fn from_u128(v: u128) -> Self {
+ v as $name
+ }
#[inline(always)]
- fn from_usize(v: usize) -> Self { v as $name }
+ fn from_usize(v: usize) -> Self {
+ v as $name
+ }
#[inline(always)]
- fn to_u8(&self) -> u8 { (*self) as u8 }
+ fn to_u8(&self) -> u8 {
+ (*self) as u8
+ }
#[inline(always)]
- fn to_u16(&self) -> u16 { (*self) as u16 }
+ fn to_u16(&self) -> u16 {
+ (*self) as u16
+ }
#[inline(always)]
- fn to_u32(&self) -> u32 { (*self) as u32 }
+ fn to_u32(&self) -> u32 {
+ (*self) as u32
+ }
#[inline(always)]
- fn to_u64(&self) -> u64 { (*self) as u64 }
+ fn to_u64(&self) -> u64 {
+ (*self) as u64
+ }
#[inline(always)]
- fn to_u128(&self) -> u128 { (*self) as u128 }
+ fn to_u128(&self) -> u128 {
+ (*self) as u128
+ }
#[inline(always)]
- fn to_usize(&self) -> usize { (*self) as usize }
+ fn to_usize(&self) -> usize {
+ (*self) as usize
+ }
#[inline(always)]
- fn from_u8_opt(v: u8) -> Option<Self> { v.try_into().ok() }
+ fn from_u8_opt(v: u8) -> Option<Self> {
+ v.try_into().ok()
+ }
#[inline(always)]
- fn from_u16_opt(v: u16) -> Option<Self> { v.try_into().ok() }
+ fn from_u16_opt(v: u16) -> Option<Self> {
+ v.try_into().ok()
+ }
#[inline(always)]
- fn from_u32_opt(v: u32) -> Option<Self> { v.try_into().ok() }
+ fn from_u32_opt(v: u32) -> Option<Self> {
+ v.try_into().ok()
+ }
#[inline(always)]
- fn from_u64_opt(v: u64) -> Option<Self> { v.try_into().ok() }
+ fn from_u64_opt(v: u64) -> Option<Self> {
+ v.try_into().ok()
+ }
#[inline(always)]
- fn from_u128_opt(v: u128) -> Option<Self> { v.try_into().ok() }
+ fn from_u128_opt(v: u128) -> Option<Self> {
+ v.try_into().ok()
+ }
#[inline(always)]
- fn from_usize_opt(v: usize) -> Option<Self> { v.try_into().ok() }
+ fn from_usize_opt(v: usize) -> Option<Self> {
+ v.try_into().ok()
+ }
#[inline(always)]
- fn to_u8_opt(&self) -> Option<u8> { (*self).try_into().ok() }
+ fn to_u8_opt(&self) -> Option<u8> {
+ (*self).try_into().ok()
+ }
#[inline(always)]
- fn to_u16_opt(&self) -> Option<u16> { (*self).try_into().ok() }
+ fn to_u16_opt(&self) -> Option<u16> {
+ (*self).try_into().ok()
+ }
#[inline(always)]
- fn to_u32_opt(&self) -> Option<u32> { (*self).try_into().ok() }
+ fn to_u32_opt(&self) -> Option<u32> {
+ (*self).try_into().ok()
+ }
#[inline(always)]
- fn to_u64_opt(&self) -> Option<u64> { (*self).try_into().ok() }
+ fn to_u64_opt(&self) -> Option<u64> {
+ (*self).try_into().ok()
+ }
#[inline(always)]
- fn to_u128_opt(&self) -> Option<u128> { (*self).try_into().ok() }
+ fn to_u128_opt(&self) -> Option<u128> {
+ (*self).try_into().ok()
+ }
#[inline(always)]
- fn to_usize_opt(&self) -> Option<usize> { (*self).try_into().ok() }
+ fn to_usize_opt(&self) -> Option<usize> {
+ (*self).try_into().ok()
+ }
}
- }
+ };
}
-prim!(u8 , 8 );
-prim!(u16 , 16 );
-prim!(u32 , 32 );
-prim!(u64 , 64 );
+prim!(u8, 8);
+prim!(u16, 16);
+prim!(u32, 32);
+prim!(u64, 64);
prim!(u128, 128);
-#![recursion_limit="256"]
+#![recursion_limit = "256"]
extern crate proc_macro;
use darling::*;
use proc_macro::TokenStream;
-use proc_macro2::{TokenStream as SynTokenStream, Literal, Span};
+use proc_macro2::{Literal, Span, TokenStream as SynTokenStream};
+use quote::*;
use std::{collections::HashSet, fmt::Display};
-use syn::{*, Result, Error};
use syn::spanned::Spanned;
-use quote::*;
+use syn::{Error, Result, *};
/// Helper function for emitting compile errors.
fn error<T>(span: Span, message: impl Display) -> Result<T> {
name: input.ident.clone(),
crate_name: attrs.crate_name.map(|x| Ident::new(&x, Span::call_site())),
explicit_mem_repr: attrs.repr.map(|x| Ident::new(&x, Span::call_site())),
- explicit_serde_repr: attrs.serialize_repr.map(|x| Ident::new(&x, Span::call_site())),
+ explicit_serde_repr: attrs
+ .serialize_repr
+ .map(|x| Ident::new(&x, Span::call_site())),
has_signed_repr: false,
has_large_repr: false,
variants: Vec::new(),
no_ops: attrs.no_ops,
no_super_impls: attrs.no_super_impls,
serialize_as_list: attrs.serialize_as_list,
- serialize_deny_unknown: attrs.serialize_deny_unknown
+ serialize_deny_unknown: attrs.serialize_deny_unknown,
}
}
self.has_large_repr = true;
Ok(())
}
- _ => error(attr_span, "Unsupported repr.")
+ _ => error(attr_span, "Unsupported repr."),
}
}
/// Adds a variant to the enumset.
if discriminant > self.max_discrim {
self.max_discrim = discriminant;
}
- self.variants.push(EnumSetValue {
- name: variant.ident.clone(),
- variant_repr: discriminant,
- });
+ self.variants
+ .push(EnumSetValue { name: variant.ident.clone(), variant_repr: discriminant });
self.used_variant_names.insert(variant.ident.to_string());
self.used_discriminants.insert(discriminant);
"u128" => self.max_discrim >= 128,
_ => error(
Span::call_site(),
- "Only `u8`, `u16`, `u32`, `u64` and `u128` are supported for serde_repr."
+ "Only `u8`, `u16`, `u32`, `u64` and `u128` are supported for serde_repr.",
)?,
};
if is_overflowed {
"u128" => self.max_discrim >= 128,
_ => error(
Span::call_site(),
- "Only `u8`, `u16`, `u32`, `u64` and `u128` are supported for repr."
+ "Only `u8`, `u16`, `u32`, `u64` and `u128` are supported for repr.",
)?,
};
if is_overflowed {
{
quote!(::enumset)
}
- },
+ }
};
let typed_enumset = quote!(#enumset::EnumSet<#name>);
let core = quote!(#enumset::__internal::core_export);
}
};
-
#[cfg(feature = "serde")]
let serde = quote!(#enumset::__internal::serde);
}
}
} else {
- quote! { }
+ quote! {}
};
quote! {
fn serialize<S: #serde::Serializer>(
};
#[cfg(not(feature = "serde"))]
- let serde_ops = quote! { };
+ let serde_ops = quote! {};
let is_uninhabited = info.variants.is_empty();
let is_zst = info.variants.len() == 1;
let variant_value: Vec<_> = info.variants.iter().map(|x| x.variant_repr).collect();
let const_field: Vec<_> = ["IS_U8", "IS_U16", "IS_U32", "IS_U64", "IS_U128"]
- .iter().map(|x| Ident::new(x, Span::call_site())).collect();
+ .iter()
+ .map(|x| Ident::new(x, Span::call_site()))
+ .collect();
let int_type: Vec<_> = ["u8", "u16", "u32", "u64", "u128"]
- .iter().map(|x| Ident::new(x, Span::call_site())).collect();
+ .iter()
+ .map(|x| Ident::new(x, Span::call_site()))
+ .collect();
quote! {
fn enum_into_u32(self) -> u32 {