feat: add display UI with splash screen, dashboard, and RSSI sparkline

Implement full SSD1306 OLED display support:
- Splash screen on boot (1.5s) with project name, version, board
- Dashboard showing radio state, config, counters, RSSI/SNR
- RSSI history sparkline (64-sample ring buffer, 2px-wide bars)
- DisplayOn/DisplayOff host commands routed via dedicated channel
- Pure render functions against generic DrawTarget (no hardware coupling)
- Display on/off control bypasses radio task entirely

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
swaitsandClaude Opus 4.6 committed 2026-03-29 20:42:54 -06:00
1 parent 7064110293
commit 3102fc747a
17624 files changed
+4564928 -38

No files matched your search

+152
View File
@@ -0,0 +1,152 @@
#[cfg(all(doc, feature = "serde"))]
use serde::{Deserialize, Serialize};
#[cfg(doc)]
use crate::EnumSet;
/// The procedural macro used to derive [`EnumSetType`], and allow enums to be used with
/// [`EnumSet`].
///
/// # Limitations
///
/// Currently, the following limitations apply to what kinds of enums this macro may be used with:
///
/// * The enum must have no data fields in any variant.
/// * Variant discriminators must be zero or positive.
/// * No variant may have a discriminator larger than `0xFFFFFFBF`.
///
/// # Additional Impls
///
/// In addition to the implementation of `EnumSetType`, this procedural macro creates multiple
/// other impls that are either required for the macro to work, or make the procedural macro more
/// ergonomic to use.
///
/// A full list of traits implemented as is follows:
///
/// * [`Copy`], [`Clone`], [`Eq`], [`PartialEq`] implementations are created to allow `EnumSet`
/// to function properly. These automatic implementations may be suppressed using
/// `#[enumset(no_super_impls)]`, but these traits must still be implemented in another way.
/// * [`PartialEq`], [`Sub`], [`BitAnd`], [`BitOr`], [`BitXor`], and [`Not`] implementations are
/// created to allow the crate to be used more ergonomically in expressions. These automatic
/// implementations may be suppressed using `#[enumset(no_ops)]`.
///
/// # Options
///
/// Options are given with `#[enumset(foo)]` annotations attached to the same enum as the derive.
/// Multiple options may be given in the same annotation using the `#[enumset(foo, bar)]` syntax.
///
/// A full list of options available is as follows:
///
/// * `#[enumset(no_super_impls)]` prevents the procedural macro from generating implementations
/// for the supertraits of `EnumSetType`. When this attribute is specified, implementations of
/// [`Copy`], [`Clone`], [`Eq`], and [`PartialEq`] must be provided manually. These impls should
/// function identically to the automatically derived versions, or unintentional behavior may be
/// a result.
/// * `#[enumset(no_ops)` prevents the procedural macro from implementing any operator traits.
/// * `#[enumset(crate_name = "enumset2")]` may be used to change the name of the `enumset` crate
/// used in the generated code. When the `proc-macro-crate` feature is enabled, enumset parses
/// `Cargo.toml` to determine the name of the crate, and this flag is unnecessary.
/// * `#[enumset(map = "…")]` controls how enum variants are mapped to bits in the `EnumSet`. For
/// more information, see the [Mapping Options](#mapping-options) section.
/// * `#[enumset(repr = "…")]` is used to control the in-memory representation of `EnumSet`s. For
/// more information, see the [Representation Options](#representation-options) section.
///
/// Additional feature may be specified when the `serde` feature is enabled. These options are
/// ignored when `serde` is not enabled. For more information, see the
/// [Serialization Options](#serialization-options) section.
///
/// ## Mapping Options
///
/// The following options exist to control how enum variants are mapped to bits in an `EnumSet`:
///
/// * `#[enumset(map = "lsb")]` maps an enum variant with a discriminator of `n` to the `n + 1`th
/// least significant bit of the enumset. If no mapping is specified, this is used by default.
/// * `#[enumset(map = "msb")]` maps an enum variant with a discriminator of `n` to the `n + 1`th
/// most significant bit of the enumset. This requires an explicit integer representation or else
/// compilation will fail.
/// * `#[enumset(map = "compact")]` maps each enum variant to an unspecified bit in the set. This
/// allows the library to use less memory than it may otherwise and allows any discrminator
/// values to be used without issue.
/// * `#[enumset(map = "mask")]` treats each enum variant's discriminator as a mask rather than a
/// bit index. Each discriminant must be a power of two, and may be of arbitrary size.
///
/// ## Representation Options
///
/// The following options exist to control the in-memory representation of an `EnumSet`:
///
/// * `#[enumset(repr = "u…")]` forces the `EnumSet` to use a specific primitive integer type.
/// Allowed types are `u8`, `u16`, `u32`, `u64` and `u128`. This allows the `EnumSet` to be
/// safely used across FFI boundaries. Additionally, the procedural macro will generate an
/// implementation of <code>[EnumSetTypeWithRepr]&lt;Repr = R&gt;</code>.
/// * `#[enumset(repr = "array")]` forces the `EnumSet` of this type to be backed with an array,
/// even if all the variants could fit into a primitive numeric type.
///
/// By default, `enumset` tries to choose the representation most suitable to the type, but no
/// guarantees are made about which it picks.
///
/// [EnumSetTypeWithRepr]: crate::traits::EnumSetTypeWithRepr
///
/// ## Serialization Options
///
/// The following options exist to control how an `EnumSet` is serialized with `serde`:
///
/// * `#[enumset(serialize_repr = "u…")]` causes the set to be serialized as a single integer
/// of the corresponding primitive type.
/// * `#[enumset(serialize_repr = "array")]` causes the set to be serialized as a list of `u64`s
/// corresponding to the [array representation](EnumSet#array-representation) of the set.
/// * `#[enumset(serialize_repr = "list")]` causes the set to be serialized as a list of enum
/// variants. This requires your enum type implement [`Serialize`] and [`Deserialize`].
/// * `#[enumset(serialize_repr = "map")]` causes the set to be serialized as map of enum variants
/// to booleans. The set contains a value if the boolean is `true`. This requires your enum type
/// implement `Serialize` and `Deserialize`.
/// * `#[enumset(serialize_deny_unknown)]` causes the generated deserializer to return an error
/// for unknown bits instead of silently ignoring them.
///
/// By default, `enumset` uses the smallest integer type that can contain all enum variants or an
/// array if there is no such integer type.
///
/// # Examples
///
/// Deriving a plain EnumSetType:
///
/// ```rust
/// # use enumset::*;
/// #[derive(EnumSetType)]
/// pub enum Enum {
/// A, B, C, D, E, F, G,
/// }
/// ```
///
/// Deriving a sparse EnumSetType:
///
/// ```rust
/// # use enumset::*;
/// #[derive(EnumSetType)]
/// pub enum SparseEnum {
/// A = 10, B = 20, C = 30, D = 127,
/// }
/// ```
///
/// Deriving an EnumSetType without adding ops:
///
/// ```rust
/// # use enumset::*;
/// #[derive(EnumSetType)]
/// #[enumset(no_ops)]
/// pub enum NoOpsEnum {
/// A, B, C, D, E, F, G,
/// }
/// ```
///
/// [`Sub`]: core::ops::Sub
/// [`BitAnd`]: core::ops::BitAnd
/// [`BitOr`]: core::ops::BitOr
/// [`BitXor`]: core::ops::BitXor
/// [`Not`]: core::ops::Not
#[cfg_attr(
not(feature = "serde"),
doc = "\n\n",
doc = "[`Serialize`]: https://docs.rs/serde/latest/serde/trait.Serialize.html\n",
doc = "[`Deserialize`]: https://docs.rs/serde/latest/serde/trait.Deserialize.html\n"
)]
pub use enumset_derive::EnumSetType;
+102
View File
@@ -0,0 +1,102 @@
#![no_std]
#![deny(missing_docs)]
#![allow(clippy::missing_safety_doc)] // The safety requirement is "use the procedural derive".
#![allow(clippy::needless_range_loop)] // range loop style is clearer in most places in enumset
#![cfg_attr(docsrs, feature(doc_cfg))]
//! A library for defining enums that can be used in compact bit sets. It supports arbitrarily
//! large enums, and has very basic support for using them in constants.
//!
//! # Cargo Features
//!
//! The following cargo features are available for this crate:
//!
//! * `serde`: Allows serialization and deserialization of the types in this crate.
//! * `alloc`: Enables the use of functions that requires an allocator.
//! * `proc-macro-crate`: Enable the use of the `proc-macro-crate` crate to allow the renaming of
//! the `enumset` crate in your user crate. This feature increases the MSRV to 1.69.0
//!
//! # Defining enums for use with EnumSet
//!
//! Enums to be used with [`EnumSet`] should be defined using `#[derive(EnumSetType)]`:
//!
//! ```rust
//! # use enumset::*;
//! #[derive(EnumSetType, Debug)]
//! pub enum Enum {
//! A, B, C, D, E, F, G,
//! }
//! ```
//!
//! For more information on more advanced use cases, see the documentation for
//! [`#[derive(EnumSetType)]`](./derive.EnumSetType.html).
//!
//! # Working with EnumSets
//!
//! EnumSets can be constructed via [`EnumSet::new()`] like a normal set. In addition,
//! `#[derive(EnumSetType)]` creates operator overloads that allow you to create EnumSets like so:
//!
//! ```rust
//! # use enumset::*;
//! # #[derive(EnumSetType, Debug)] pub enum Enum { A, B, C, D, E, F, G }
//! let new_set = Enum::A | Enum::C | Enum::G;
//! assert_eq!(new_set.len(), 3);
//! ```
//!
//! All bitwise operations you would expect to work on bitsets also work on both EnumSets and
//! enums with `#[derive(EnumSetType)]`:
//! ```rust
//! # use enumset::*;
//! # #[derive(EnumSetType, Debug)] pub enum Enum { A, B, C, D, E, F, G }
//! // Intersection of sets
//! assert_eq!((Enum::A | Enum::B) & Enum::C, EnumSet::empty());
//! assert_eq!((Enum::A | Enum::B) & Enum::A, Enum::A);
//! assert_eq!(Enum::A & Enum::B, EnumSet::empty());
//!
//! // Symmetric difference of sets
//! assert_eq!((Enum::A | Enum::B) ^ (Enum::B | Enum::C), Enum::A | Enum::C);
//! assert_eq!(Enum::A ^ Enum::C, Enum::A | Enum::C);
//!
//! // Difference of sets
//! assert_eq!((Enum::A | Enum::B | Enum::C) - Enum::B, Enum::A | Enum::C);
//!
//! // Complement of sets
//! assert_eq!(!(Enum::E | Enum::G), Enum::A | Enum::B | Enum::C | Enum::D | Enum::F);
//! ```
//!
//! The [`enum_set!`] macro allows you to create EnumSets in constant contexts:
//!
//! ```rust
//! # use enumset::*;
//! # #[derive(EnumSetType, Debug)] pub enum Enum { A, B, C, D, E, F, G }
//! const CONST_SET: EnumSet<Enum> = enum_set!(Enum::A | Enum::B);
//! assert_eq!(CONST_SET, Enum::A | Enum::B);
//! ```
//!
//! Mutable operations on the [`EnumSet`] otherwise similarly to Rust's builtin sets:
//!
//! ```rust
//! # use enumset::*;
//! # #[derive(EnumSetType, Debug)] pub enum Enum { A, B, C, D, E, F, G }
//! let mut set = EnumSet::new();
//! set.insert(Enum::A);
//! set.insert_all(Enum::E | Enum::G);
//! assert!(set.contains(Enum::A));
//! assert!(!set.contains(Enum::B));
//! assert_eq!(set, Enum::A | Enum::E | Enum::G);
//! ```
#[cfg(feature = "alloc")]
extern crate alloc;
mod macros;
mod derive;
mod repr;
mod set;
mod traits;
pub use crate::derive::EnumSetType;
pub use crate::macros::__internal;
pub use crate::set::{EnumSet, EnumSetIter};
pub use crate::traits::{EnumSetType, EnumSetTypeWithRepr};
+305
View File
@@ -0,0 +1,305 @@
/// Everything in this module is internal API and may change at any time.
#[doc(hidden)]
pub mod __internal {
/// A reexport of core to allow our macros to be generic to std vs core.
pub use ::core as core_export;
/// A reexport of serde so our users don't have to also have a serde dependency.
#[cfg(feature = "serde")]
pub use serde;
/// Reexports of internal types
pub use crate::{
repr::{ArrayRepr, EnumSetTypeRepr},
traits::{EnumSetConstHelper, EnumSetTypePrivate},
};
#[cfg(feature = "serde")]
#[doc(hidden)]
#[macro_export]
macro_rules! __if_serde {
($($tt:tt)*) => {
$($tt)*
};
}
#[cfg(not(feature = "serde"))]
#[doc(hidden)]
#[macro_export]
macro_rules! __if_serde {
($($tt:tt)*) => {};
}
/// Macro to wrap serde-related code generated by the derive, discarding it
/// if serde support is not enabled.
pub use __if_serde;
pub use crate::macros::set;
}
/// Helper functions for sets.
pub mod set {
use crate::__internal::EnumSetConstHelper;
use crate::{EnumSet, EnumSetType};
/// Retrieves the helper used in constant time operations.
#[inline(always)]
pub const fn op_helper<T: EnumSetConstHelper>(_: &T) -> T::ConstOpHelper {
T::CONST_OP_HELPER
}
/// Retrieves the helper used in constant time conversions.
#[inline(always)]
pub const fn init_helper<T: EnumSetConstHelper>(_: &T) -> T::ConstInitHelper {
T::CONST_INIT_HELPER
}
/// Gets the underlying repr from an EnumSet
#[inline(always)]
pub const fn get<T: EnumSetType>(set: EnumSet<T>) -> T::Repr {
set.repr
}
/// Constructs an EnumSet from the underlying repr
#[inline(always)]
pub const fn new<T: EnumSetType>(set: T::Repr) -> EnumSet<T> {
EnumSet { repr: set }
}
}
/// Creates a EnumSet literal, which can be used in const contexts.
///
/// The syntax used is `enum_set!(Type::A | Type::B | Type::C)`. Each variant must be of the same
/// type, or an error will occur at compile-time.
///
/// This macro accepts trailing `|`s to allow easier use in other macros.
///
/// # Performance
///
/// This macro is designed for use in const contexts, not for execution as normal code. It may be
/// significantly slower than normal code outside const contexts.
///
/// In normal code, directly use `Type::A | Type::B | Type::C` instead.
///
/// # Examples
///
/// ```rust
/// # use enumset::*;
/// # #[derive(EnumSetType, Debug)] enum Enum { A, B, C }
/// const CONST_SET: EnumSet<Enum> = enum_set!(Enum::A | Enum::B);
/// assert_eq!(CONST_SET, Enum::A | Enum::B);
/// ```
///
/// This macro is strongly typed. For example, the following will not compile:
///
/// ```compile_fail
/// # use enumset::*;
/// # #[derive(EnumSetType, Debug)] enum Enum { A, B, C }
/// # #[derive(EnumSetType, Debug)] enum Enum2 { A, B, C }
/// let type_error = enum_set!(Enum::A | Enum2::B);
/// ```
#[macro_export]
macro_rules! enum_set {
($(|)*) => {
$crate::EnumSet::empty()
};
($value:path $(|)*) => {
{
$crate::__internal::set::init_helper(&$value).const_only($value)
}
};
($value:path | $($rest:path)|* $(|)*) => {
$crate::enum_set_union!($value, $($rest,)*)
};
}
/// Computes the union of multiple enums or constants enumset at compile time.
///
/// The syntax used is `enum_set_union!(ENUM_A, ENUM_B, ENUM_C)`, computing the equivalent of
/// `ENUM_A | ENUM_B | ENUM_C` at compile time. Each variant must be of the same type, or an error
/// will occur at compile-time.
///
/// # Performance
///
/// This macro is designed for use in const contexts, not for execution as normal code. It may be
/// significantly slower than normal code outside const contexts.
///
/// In normal code, directly use the `|` operator instead.
///
/// # Examples
///
/// ```rust
/// # use enumset::*;
/// # #[derive(EnumSetType, Debug)] enum Enum { A, B, C }
/// const CONST_SET: EnumSet<Enum> = enum_set_union!(Enum::A, Enum::B);
/// assert_eq!(CONST_SET, Enum::A | Enum::B);
/// ```
#[macro_export]
macro_rules! enum_set_union {
($value:path $(,)?) => {
$crate::enum_set!($value)
};
($value:path, $($rest:path),* $(,)?) => {
{
let op_helper = $crate::__internal::set::op_helper(&$value);
let value = $crate::enum_set!($value);
$(let value = {
let new = $crate::enum_set!($rest);
op_helper.const_union(value, new)
};)*
value
}
};
}
/// Computes the intersection of multiple enums or constants enumset at compile time.
///
/// The syntax used is `enum_set_intersection!(ENUM_A, ENUM_B, ENUM_C)`, computing the equivalent
/// of `ENUM_A & ENUM_B & ENUM_C` at compile time. Each variant must be of the same type, or an
/// error will occur at compile-time.
///
/// # Performance
///
/// This macro is designed for use in const contexts, not for execution as normal code. It may be
/// significantly slower than normal code outside const contexts.
///
/// In normal code, directly use the `&` operator instead.
///
/// # Examples
///
/// ```rust
/// # use enumset::*;
/// # #[derive(EnumSetType, Debug)] enum Enum { A, B, C, D }
/// const SET_A: EnumSet<Enum> = enum_set!(Enum::A | Enum::B);
/// const SET_B: EnumSet<Enum> = enum_set!(Enum::B | Enum::C);
/// const CONST_SET: EnumSet<Enum> = enum_set_intersection!(SET_A, SET_B);
/// assert_eq!(CONST_SET, Enum::B);
/// ```
#[macro_export]
macro_rules! enum_set_intersection {
($value:path $(,)?) => {
$crate::enum_set!($value)
};
($value:path, $($rest:path),* $(,)?) => {
{
let op_helper = $crate::__internal::set::op_helper(&$value);
let value = $crate::enum_set!($value);
$(let value = {
let new = $crate::enum_set!($rest);
op_helper.const_intersection(value, new)
};)*
value
}
};
}
/// Computes the complement of an enums or constants enumset at compile time.
///
/// # Performance
///
/// This macro is designed for use in const contexts, not for execution as normal code. It may be
/// significantly slower than normal code outside const contexts.
///
/// In normal code, directly use the `!` operator instead.
///
/// # Examples
///
/// ```rust
/// # use enumset::*;
/// #[derive(EnumSetType, Debug)]
/// enum Enum { A, B, C, D }
///
/// const SET: EnumSet<Enum> = enum_set!(Enum::B | Enum::C);
/// const CONST_SET: EnumSet<Enum> = enum_set_complement!(SET);
/// assert_eq!(CONST_SET, Enum::A | Enum::D);
/// ```
#[macro_export]
macro_rules! enum_set_complement {
($value:path $(,)?) => {{
let op_helper = $crate::__internal::set::op_helper(&$value);
let value = $crate::enum_set!($value);
op_helper.const_complement(value)
}};
}
/// Computes the difference of multiple enums or constants enumset at compile time.
///
/// The syntax used is `enum_set_difference!(ENUM_A, ENUM_B, ENUM_C)`, computing the equivalent
/// of `ENUM_A - ENUM_B - ENUM_C` at compile time. Each variant must be of the same type, or an
/// error will occur at compile-time.
///
/// # Performance
///
/// This macro is designed for use in const contexts, not for execution as normal code. It may be
/// significantly slower than normal code outside const contexts.
///
/// In normal code, directly use the `-` operator instead.
///
/// # Examples
///
/// ```rust
/// # use enumset::*;
/// # #[derive(EnumSetType, Debug)] enum Enum { A, B, C, D }
/// const SET_A: EnumSet<Enum> = enum_set!(Enum::A | Enum::B | Enum::D);
/// const SET_B: EnumSet<Enum> = enum_set!(Enum::B | Enum::C);
/// const CONST_SET: EnumSet<Enum> = enum_set_symmetric_difference!(SET_A, SET_B);
/// assert_eq!(CONST_SET, Enum::A | Enum::C | Enum::D);
/// ```
#[macro_export]
macro_rules! enum_set_difference {
($value:path $(,)?) => {
$crate::enum_set!($value)
};
($value:path, $($rest:path),* $(,)?) => {
{
let op_helper = $crate::__internal::set::op_helper(&$value);
let value = $crate::enum_set!($value);
$(let value = {
let new = $crate::enum_set!($rest);
op_helper.const_intersection(value, op_helper.const_complement(new))
};)*
value
}
};
}
/// Computes the symmetric difference of multiple enums or constants enumset at compile time.
///
/// The syntax used is `enum_set_symmetric_difference!(ENUM_A, ENUM_B, ENUM_C)`, computing the
/// equivalent of `ENUM_A ^ ENUM_B ^ ENUM_C` at compile time. Each variant must be of the same
/// type, or an error will occur at compile-time.
///
/// # Performance
///
/// This macro is designed for use in const contexts, not for execution as normal code. It may be
/// significantly slower than normal code outside const contexts.
///
/// In normal code, directly use the `^` operator instead.
///
/// # Examples
///
/// ```rust
/// # use enumset::*;
/// # #[derive(EnumSetType, Debug)] enum Enum { A, B, C, D }
/// const SET_A: EnumSet<Enum> = EnumSet::all();
/// const SET_B: EnumSet<Enum> = enum_set!(Enum::B | Enum::C);
/// const CONST_SET: EnumSet<Enum> = enum_set_difference!(SET_A, SET_B);
/// assert_eq!(CONST_SET, Enum::A | Enum::D);
/// ```
#[macro_export]
macro_rules! enum_set_symmetric_difference {
($value:path $(,)?) => {
$crate::enum_set!($value)
};
($value:path, $($rest:path),* $(,)?) => {
{
let op_helper = $crate::__internal::set::op_helper(&$value);
let value = $crate::enum_set!($value);
$(let value = {
let new = $crate::enum_set!($rest);
op_helper.const_symmetric_difference(value, new)
};)*
value
}
};
}
+317
View File
@@ -0,0 +1,317 @@
use crate::repr::primitive::PrimitiveIter;
use crate::repr::EnumSetTypeRepr;
use core::ops::*;
/// An implementation of `EnumSetTypeRepr` based on an arbitrary size array.
///
/// `N` **must** not be `0`, or else everything will break.
#[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Debug, Hash)]
pub struct ArrayRepr<const N: usize>(pub [u64; N]);
impl<const N: usize> ArrayRepr<N> {
fn split_bit(bit: u32) -> (usize, u32) {
(bit as usize / 64, bit % 64)
}
}
impl<const N: usize> BitAnd for ArrayRepr<N> {
type Output = Self;
fn bitand(mut self, rhs: Self) -> Self::Output {
for i in 0..N {
self.0[i] &= rhs.0[i];
}
self
}
}
impl<const N: usize> BitOr for ArrayRepr<N> {
type Output = Self;
fn bitor(mut self, rhs: Self) -> Self::Output {
for i in 0..N {
self.0[i] |= rhs.0[i];
}
self
}
}
impl<const N: usize> BitXor for ArrayRepr<N> {
type Output = Self;
fn bitxor(mut self, rhs: Self) -> Self::Output {
for i in 0..N {
self.0[i] ^= rhs.0[i];
}
self
}
}
impl<const N: usize> Not for ArrayRepr<N> {
type Output = Self;
fn not(mut self) -> Self::Output {
for i in 0..N {
self.0[i] = !self.0[i];
}
self
}
}
impl<const N: usize> EnumSetTypeRepr for ArrayRepr<N> {
const PREFERRED_ARRAY_LEN: usize = N;
const WIDTH: u32 = N as u32 * 64;
const EMPTY: Self = ArrayRepr([0; N]);
fn is_empty(&self) -> bool {
self.0.iter().all(|x| *x == 0)
}
fn add_bit(&mut self, bit: u32) {
let (idx, bit) = Self::split_bit(bit);
self.0[idx].add_bit(bit);
}
fn remove_bit(&mut self, bit: u32) {
let (idx, bit) = Self::split_bit(bit);
self.0[idx].remove_bit(bit);
}
fn has_bit(&self, bit: u32) -> bool {
let (idx, bit) = Self::split_bit(bit);
self.0[idx].has_bit(bit)
}
fn count_ones(&self) -> u32 {
self.0.iter().map(|x| x.count_ones()).sum()
}
fn and_not(&self, other: Self) -> Self {
let mut new = Self([0; N]);
for i in 0..N {
new.0[i] = self.0[i] & !other.0[i];
}
new
}
type Iter = ArrayIter<N>;
fn iter(self) -> Self::Iter {
ArrayIter::new(self)
}
fn from_u8(v: u8) -> Self {
Self::from_u64(v as u64)
}
fn from_u16(v: u16) -> Self {
Self::from_u64(v as u64)
}
fn from_u32(v: u32) -> Self {
Self::from_u64(v as u64)
}
fn from_u64(v: u64) -> Self {
let mut new = Self([0; N]);
new.0[0] = v;
new
}
fn from_u128(v: u128) -> Self {
let mut new = Self([0; N]);
new.0[0] = v as u64;
if N != 1 {
new.0[1] = (v >> 64) as u64;
}
new
}
fn from_usize(v: usize) -> Self {
Self::from_u64(v as u64)
}
fn from_u8_opt(v: u8) -> Option<Self> {
Some(Self::from_u8(v))
}
fn from_u16_opt(v: u16) -> Option<Self> {
Some(Self::from_u16(v))
}
fn from_u32_opt(v: u32) -> Option<Self> {
Some(Self::from_u32(v))
}
fn from_u64_opt(v: u64) -> Option<Self> {
Some(Self::from_u64(v))
}
fn from_u128_opt(v: u128) -> Option<Self> {
if N == 1 && (v >> 64) != 0 {
None
} else {
Some(Self::from_u128(v))
}
}
fn from_usize_opt(v: usize) -> Option<Self> {
Some(Self::from_usize(v))
}
fn to_u8(&self) -> u8 {
self.to_u64().to_u8()
}
fn to_u16(&self) -> u16 {
self.to_u64().to_u16()
}
fn to_u32(&self) -> u32 {
self.to_u64().to_u32()
}
fn to_u64(&self) -> u64 {
self.0[0]
}
fn to_u128(&self) -> u128 {
let hi = if N == 1 { 0 } else { (self.0[1] as u128) << 64 };
self.0[0] as u128 | hi
}
fn to_usize(&self) -> usize {
self.to_u64().to_usize()
}
fn to_u8_opt(&self) -> Option<u8> {
self.to_u64_opt().and_then(|x| x.to_u8_opt())
}
fn to_u16_opt(&self) -> Option<u16> {
self.to_u64_opt().and_then(|x| x.to_u16_opt())
}
fn to_u32_opt(&self) -> Option<u32> {
self.to_u64_opt().and_then(|x| x.to_u32_opt())
}
fn to_u64_opt(&self) -> Option<u64> {
for i in 1..N {
if self.0[i] != 0 {
return None;
}
}
Some(self.to_u64())
}
fn to_u128_opt(&self) -> Option<u128> {
for i in 2..N {
if self.0[i] != 0 {
return None;
}
}
Some(self.to_u128())
}
fn to_usize_opt(&self) -> Option<usize> {
self.to_u64_opt().and_then(|x| x.to_usize_opt())
}
fn to_u64_array<const O: usize>(&self) -> [u64; O] {
let mut array = [0; O];
let copy_len = if N < O { N } else { O };
array[..copy_len].copy_from_slice(&self.0[..copy_len]);
array
}
fn to_u64_array_opt<const O: usize>(&self) -> Option<[u64; O]> {
if N > O {
for i in O..N {
if self.0[i] != 0 {
return None;
}
}
}
Some(self.to_u64_array())
}
fn from_u64_array<const O: usize>(v: [u64; O]) -> Self {
ArrayRepr(ArrayRepr::<O>(v).to_u64_array::<N>())
}
fn from_u64_array_opt<const O: usize>(v: [u64; O]) -> Option<Self> {
ArrayRepr::<O>(v).to_u64_array_opt::<N>().map(ArrayRepr)
}
fn to_u64_slice(&self, out: &mut [u64]) {
let copy_len = if N < out.len() { N } else { out.len() };
out[..copy_len].copy_from_slice(&self.0[..copy_len]);
for i in copy_len..out.len() {
out[i] = 0;
}
}
fn to_u64_slice_opt(&self, out: &mut [u64]) -> Option<()> {
if N > out.len() {
for i in out.len()..N {
if self.0[i] != 0 {
return None;
}
}
}
self.to_u64_slice(out);
Some(())
}
fn from_u64_slice(v: &[u64]) -> Self {
let mut new = ArrayRepr([0; N]);
let copy_len = if N < v.len() { N } else { v.len() };
new.0[..copy_len].copy_from_slice(&v[..copy_len]);
new
}
fn from_u64_slice_opt(v: &[u64]) -> Option<Self> {
if v.len() > N {
for i in N..v.len() {
if v[i] != 0 {
return None;
}
}
}
Some(Self::from_u64_slice(v))
}
}
#[derive(Clone, Debug)]
pub struct ArrayIter<const N: usize> {
data: [PrimitiveIter<u64>; N],
done: bool,
idx_f: usize,
idx_r: usize,
}
impl<const N: usize> ArrayIter<N> {
pub fn new(array: ArrayRepr<N>) -> Self {
let mut new = [PrimitiveIter(0); N];
for i in 0..N {
new[i] = PrimitiveIter(array.0[i])
}
ArrayIter { data: new, done: false, idx_f: 0, idx_r: N - 1 }
}
}
impl<const N: usize> Iterator for ArrayIter<N> {
type Item = u32;
fn next(&mut self) -> Option<Self::Item> {
if self.done {
return None;
}
loop {
if let Some(x) = unsafe { self.data.get_unchecked_mut(self.idx_f).next() } {
return Some(self.idx_f as u32 * 64 + x);
} else {
if self.idx_f == N - 1 || self.idx_f > self.idx_r {
break;
}
self.idx_f += 1;
}
}
self.done = true;
None
}
fn size_hint(&self) -> (usize, Option<usize>) {
let mut sum = 0;
for i in self.idx_f..self.idx_r + 1 {
sum += self.data[i].0.count_ones() as usize;
}
(sum, Some(sum))
}
}
impl<const N: usize> DoubleEndedIterator for ArrayIter<N> {
fn next_back(&mut self) -> Option<Self::Item> {
if self.done {
return None;
}
loop {
if let Some(x) = unsafe { self.data.get_unchecked_mut(self.idx_r).next_back() } {
return Some(self.idx_r as u32 * 64 + x);
} else {
if self.idx_r == 0 || self.idx_f > self.idx_r {
break;
}
self.idx_r -= 1;
}
}
self.done = true;
None
}
}
+90
View File
@@ -0,0 +1,90 @@
#![allow(missing_docs)]
mod array;
mod primitive;
use core::fmt::Debug;
use core::hash::Hash;
use core::ops::*;
/// A trait marking valid underlying bitset storage types and providing the
/// operations `EnumSet` and related types use.
///
/// # Safety
///
/// Note that `iter` *MUST* be implemented correctly and only return bits that
/// are actually set in the representation, or else it will cause undefined
/// behavior upstream in `EnumSet`.
pub trait EnumSetTypeRepr :
// Basic traits used to derive traits
Copy +
Ord +
Eq +
Debug +
Hash +
// Operations used by enumset
BitAnd<Output = Self> +
BitOr<Output = Self> +
BitXor<Output = Self> +
Not<Output = Self> +
{
const PREFERRED_ARRAY_LEN: usize;
const WIDTH: u32;
const EMPTY: Self;
fn is_empty(&self) -> bool;
fn add_bit(&mut self, bit: u32);
fn remove_bit(&mut self, bit: u32);
fn has_bit(&self, bit: u32) -> bool;
fn count_ones(&self) -> u32;
fn and_not(&self, other: Self) -> Self;
type Iter: Iterator<Item = u32> + DoubleEndedIterator + Clone + Debug;
fn iter(self) -> Self::Iter;
fn from_u8(v: u8) -> Self;
fn from_u16(v: u16) -> Self;
fn from_u32(v: u32) -> Self;
fn from_u64(v: u64) -> Self;
fn from_u128(v: u128) -> Self;
fn from_usize(v: usize) -> Self;
fn to_u8(&self) -> u8;
fn to_u16(&self) -> u16;
fn to_u32(&self) -> u32;
fn to_u64(&self) -> u64;
fn to_u128(&self) -> u128;
fn to_usize(&self) -> usize;
fn from_u8_opt(v: u8) -> Option<Self>;
fn from_u16_opt(v: u16) -> Option<Self>;
fn from_u32_opt(v: u32) -> Option<Self>;
fn from_u64_opt(v: u64) -> Option<Self>;
fn from_u128_opt(v: u128) -> Option<Self>;
fn from_usize_opt(v: usize) -> Option<Self>;
fn to_u8_opt(&self) -> Option<u8>;
fn to_u16_opt(&self) -> Option<u16>;
fn to_u32_opt(&self) -> Option<u32>;
fn to_u64_opt(&self) -> Option<u64>;
fn to_u128_opt(&self) -> Option<u128>;
fn to_usize_opt(&self) -> Option<usize>;
fn to_u64_array<const O: usize>(&self) -> [u64; O];
fn to_u64_array_opt<const O: usize>(&self) -> Option<[u64; O]>;
fn from_u64_array<const O: usize>(v: [u64; O]) -> Self;
fn from_u64_array_opt<const O: usize>(v: [u64; O]) -> Option<Self>;
fn to_u64_slice(&self, out: &mut [u64]);
#[must_use]
fn to_u64_slice_opt(&self, out: &mut [u64]) -> Option<()>;
fn from_u64_slice(v: &[u64]) -> Self;
fn from_u64_slice_opt(v: &[u64]) -> Option<Self>;
}
pub use array::ArrayRepr;
+309
View File
@@ -0,0 +1,309 @@
use crate::repr::EnumSetTypeRepr;
pub trait Primitive {
fn leading_zeros(&self) -> u32;
fn trailing_zeros(&self) -> u32;
}
macro_rules! prim {
($name:ty, $width:expr, $preferred_array_len:expr) => {
const _: () = {
fn lo(v: $name) -> u64 {
v as u64
}
fn hi(v: $name) -> u64 {
((v as u128) >> 64) as u64
}
impl EnumSetTypeRepr for $name {
const PREFERRED_ARRAY_LEN: usize = $preferred_array_len;
const WIDTH: u32 = $width;
const EMPTY: Self = 0;
#[inline(always)]
fn is_empty(&self) -> bool {
*self == 0
}
#[inline(always)]
fn add_bit(&mut self, bit: u32) {
*self |= 1 << bit as $name;
}
#[inline(always)]
fn remove_bit(&mut self, bit: u32) {
*self &= !(1 << bit as $name);
}
#[inline(always)]
fn has_bit(&self, bit: u32) -> bool {
(self & (1 << bit as $name)) != 0
}
#[inline(always)]
fn count_ones(&self) -> u32 {
(*self).count_ones()
}
#[inline(always)]
fn and_not(&self, other: Self) -> Self {
(*self) & !other
}
type Iter = PrimitiveIter<Self>;
#[inline]
fn iter(self) -> Self::Iter {
PrimitiveIter(self)
}
#[inline(always)]
fn from_u8(v: u8) -> Self {
v as $name
}
#[inline(always)]
fn from_u16(v: u16) -> Self {
v as $name
}
#[inline(always)]
fn from_u32(v: u32) -> Self {
v as $name
}
#[inline(always)]
fn from_u64(v: u64) -> Self {
v as $name
}
#[inline(always)]
fn from_u128(v: u128) -> Self {
v as $name
}
#[inline(always)]
fn from_usize(v: usize) -> Self {
v as $name
}
#[inline(always)]
fn to_u8(&self) -> u8 {
(*self) as u8
}
#[inline(always)]
fn to_u16(&self) -> u16 {
(*self) as u16
}
#[inline(always)]
fn to_u32(&self) -> u32 {
(*self) as u32
}
#[inline(always)]
fn to_u64(&self) -> u64 {
(*self) as u64
}
#[inline(always)]
fn to_u128(&self) -> u128 {
(*self) as u128
}
#[inline(always)]
fn to_usize(&self) -> usize {
(*self) as usize
}
#[inline(always)]
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()
}
#[inline(always)]
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()
}
#[inline(always)]
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()
}
#[inline(always)]
fn to_u8_opt(&self) -> Option<u8> {
(*self).try_into().ok()
}
#[inline(always)]
fn to_u16_opt(&self) -> Option<u16> {
(*self).try_into().ok()
}
#[inline(always)]
fn to_u32_opt(&self) -> Option<u32> {
(*self).try_into().ok()
}
#[inline(always)]
fn to_u64_opt(&self) -> Option<u64> {
(*self).try_into().ok()
}
#[inline(always)]
fn to_u128_opt(&self) -> Option<u128> {
(*self).try_into().ok()
}
#[inline(always)]
fn to_usize_opt(&self) -> Option<usize> {
(*self).try_into().ok()
}
#[inline(always)]
fn to_u64_array<const O: usize>(&self) -> [u64; O] {
let mut array = [0; O];
if O > 0 {
array[0] = lo(*self);
}
if O > 1 && $preferred_array_len == 2 {
array[1] = hi(*self);
}
array
}
#[inline(always)]
fn to_u64_array_opt<const O: usize>(&self) -> Option<[u64; O]> {
if O == 0 && *self != 0 {
None
} else if O == 1 && hi(*self) != 0 {
None
} else {
Some(self.to_u64_array())
}
}
#[inline(always)]
fn from_u64_array<const O: usize>(v: [u64; O]) -> Self {
if O == 0 {
0
} else if O > 1 && $preferred_array_len == 2 {
Self::from_u128(v[0] as u128 | ((v[1] as u128) << 64))
} else {
Self::from_u64(v[0])
}
}
#[inline(always)]
fn from_u64_array_opt<const O: usize>(v: [u64; O]) -> Option<Self> {
if O == 0 {
Some(0)
} else if O == 1 {
Self::from_u64_opt(v[0])
} else {
for i in 2..O {
if v[i] != 0 {
return None;
}
}
Self::from_u128_opt(v[0] as u128 | ((v[1] as u128) << 64))
}
}
#[inline(always)]
fn to_u64_slice(&self, out: &mut [u64]) {
if out.len() > 0 {
out[0] = lo(*self);
}
if out.len() > 1 && $preferred_array_len == 2 {
out[1] = hi(*self);
}
for i in $preferred_array_len..out.len() {
out[i] = 0;
}
}
#[inline(always)]
fn to_u64_slice_opt(&self, out: &mut [u64]) -> Option<()> {
if out.len() == 0 && *self != 0 {
None
} else if out.len() == 1 && hi(*self) != 0 {
None
} else {
self.to_u64_slice(out);
Some(())
}
}
#[inline(always)]
fn from_u64_slice(v: &[u64]) -> Self {
if v.len() == 0 {
0
} else if v.len() > 1 && $preferred_array_len == 2 {
Self::from_u128(v[0] as u128 | ((v[1] as u128) << 64))
} else {
Self::from_u64(v[0])
}
}
#[inline(always)]
fn from_u64_slice_opt(v: &[u64]) -> Option<Self> {
if v.len() == 0 {
Some(0)
} else if v.len() == 1 {
Self::from_u64_opt(v[0])
} else {
for i in 2..v.len() {
if v[i] != 0 {
return None;
}
}
Self::from_u128_opt(v[0] as u128 | ((v[1] as u128) << 64))
}
}
}
impl Primitive for $name {
#[inline(always)]
fn leading_zeros(&self) -> u32 {
(*self).leading_zeros()
}
#[inline(always)]
fn trailing_zeros(&self) -> u32 {
(*self).trailing_zeros()
}
}
};
};
}
prim!(u8, 8, 1);
prim!(u16, 16, 1);
prim!(u32, 32, 1);
prim!(u64, 64, 1);
prim!(u128, 128, 2);
#[derive(Copy, Clone, Debug)]
#[repr(transparent)]
pub struct PrimitiveIter<T: EnumSetTypeRepr + Primitive>(pub T);
impl<T: EnumSetTypeRepr + Primitive> Iterator for PrimitiveIter<T> {
type Item = u32;
fn next(&mut self) -> Option<Self::Item> {
if self.0.is_empty() {
None
} else {
let bit = self.0.trailing_zeros();
self.0.remove_bit(bit);
Some(bit)
}
}
fn size_hint(&self) -> (usize, Option<usize>) {
let left = self.0.count_ones() as usize;
(left, Some(left))
}
}
impl<T: EnumSetTypeRepr + Primitive> DoubleEndedIterator for PrimitiveIter<T> {
fn next_back(&mut self) -> Option<Self::Item> {
if self.0.is_empty() {
None
} else {
let bit = T::WIDTH - 1 - self.0.leading_zeros();
self.0.remove_bit(bit);
Some(bit)
}
}
}
impl<T: EnumSetTypeRepr + Primitive> ExactSizeIterator for PrimitiveIter<T> {}
+917
View File
@@ -0,0 +1,917 @@
use crate::repr::EnumSetTypeRepr;
use crate::traits::{EnumSetConstHelper, EnumSetType};
use crate::EnumSetTypeWithRepr;
use core::cmp::Ordering;
use core::fmt::{Debug, Display, Formatter};
use core::hash::{Hash, Hasher};
use core::iter::Sum;
use core::ops::{
BitAnd, BitAndAssign, BitOr, BitOrAssign, BitXor, BitXorAssign, Not, Sub, SubAssign,
};
#[cfg(feature = "serde")]
use serde::{Deserialize, Serialize};
/// An efficient set type for enums.
///
/// It is implemented using a bitset stored using the smallest integer that can fit all bits
/// in the underlying enum. In general, an enum variant with a discriminator of `n` is stored in
/// the nth least significant bit (corresponding with a mask of, e.g. `1 << enum as u32`).
///
/// # Numeric representation
///
/// `EnumSet` is internally implemented using integer types, and as such can be easily converted
/// from and to numbers.
///
/// Each bit of the underlying integer corresponds to at most one particular enum variant. If the
/// corresponding bit for a variant is set, it present in the set. Bits that do not correspond to
/// any variant are always unset.
///
/// By default, each enum variant is stored in a bit corresponding to its discriminator. An enum
/// variant with a discriminator of `n` is stored in the `n + 1`th least significant bit
/// (corresponding to a mask of e.g. `1 << enum as u32`).
///
/// The [`#[enumset(map = "…")]`](derive@crate::EnumSetType#mapping-options) attribute can be used
/// to control this mapping.
///
/// # Array representation
///
/// Sets with more than 128 variants are instead stored with an underlying array of `u64`s. This
/// is treated as if it was a single large integer. The `n`th least significant bit of this integer
/// is stored in the `n % 64`th least significant bit of the `n / 64`th element in the array.
///
/// # Serialization
///
/// When the `serde` feature is enabled, `EnumSet`s can be serialized and deserialized using
/// the `serde` crate.
///
/// By default, `EnumSet` is serialized by directly writing out a single integer containing the
/// numeric representation of the bitset. The integer type used is the smallest one that can fit
/// the largest variant in the enum. If no integer type is large enough, instead the `EnumSet` is
/// serialized as an array of `u64`s containing the array representation. Unknown bits are ignored
/// and silently removed from the bitset when deserializing.
///
/// The exact serialization format can be controlled with additional attributes on the enum type.
/// For more information, see the documentation for
/// [Serialization Options](derive@crate::EnumSetType#serialization-options).
///
/// # FFI Safety
///
/// By default, there are no guarantees about the underlying representation of an `EnumSet`. To use
/// them safely across FFI boundaries, the
/// [`#[enumset(repr = "…")]`](derive@crate::EnumSetType#representation-options) attribute must be
/// used with a primitive integer type. For example:
///
/// ```
/// # use enumset::*;
/// #
/// # mod ffi_impl {
/// # // This example “foreign” function is actually written in Rust, but for the sake
/// # // of example, we'll pretend it's written in C.
/// # #[no_mangle]
/// # extern "C" fn some_foreign_function(set: u32) -> u32 {
/// # set & 0b100
/// # }
/// # }
/// #
/// extern "C" {
/// // This function is written in C like:
/// // uint32_t some_foreign_function(uint32_t set) { … }
/// fn some_foreign_function(set: EnumSet<MyEnum>) -> EnumSet<MyEnum>;
/// }
///
/// #[derive(Debug, EnumSetType)]
/// #[enumset(repr = "u32")]
/// enum MyEnum { A, B, C }
///
/// let set: EnumSet<MyEnum> = enum_set!(MyEnum::A | MyEnum::C);
///
/// let new_set: EnumSet<MyEnum> = unsafe { some_foreign_function(set) };
/// assert_eq!(new_set, enum_set!(MyEnum::C));
/// ```
///
/// When an `EnumSet<T>` is received via FFI, all bits that don't correspond to an enum variant
/// of `T` must be set to `0`. Behavior is **undefined** if any of these bits are set to `1`.
#[derive(Copy, Clone, PartialEq, Eq)]
#[repr(transparent)]
pub struct EnumSet<T: EnumSetType> {
pub(crate) repr: T::Repr,
}
//region EnumSet operations
impl<T: EnumSetType> EnumSet<T> {
const EMPTY_REPR: Self = EnumSet { repr: T::Repr::EMPTY };
const ALL_REPR: Self = EnumSet { repr: T::ALL_BITS };
/// Creates an empty `EnumSet`.
#[inline(always)]
pub const fn new() -> Self {
Self::EMPTY_REPR
}
/// Returns an `EnumSet` containing a single element.
#[inline(always)]
pub fn only(t: T) -> Self {
let mut set = Self::new();
set.insert(t);
set
}
/// Creates an empty `EnumSet`.
///
/// This is an alias for [`EnumSet::new`].
#[inline(always)]
pub const fn empty() -> Self {
Self::EMPTY_REPR
}
/// Returns an `EnumSet` containing all valid variants of the enum.
#[inline(always)]
pub const fn all() -> Self {
Self::ALL_REPR
}
/// Total number of bits used by this type. Note that the actual amount of space used is
/// rounded up to the next highest integer type (`u8`, `u16`, `u32`, `u64`, or `u128`).
///
/// This is the same as [`EnumSet::variant_count`] except in enums with "sparse" variants.
/// (e.g. `enum Foo { A = 10, B = 20 }`)
#[inline(always)]
pub const fn bit_width() -> u32 {
T::BIT_WIDTH
}
/// The number of valid variants that this type can contain.
///
/// This is the same as [`EnumSet::bit_width`] except in enums with "sparse" variants.
/// (e.g. `enum Foo { A = 10, B = 20 }`)
#[inline(always)]
pub const fn variant_count() -> u32 {
T::VARIANT_COUNT
}
/// Returns the number of elements in this set.
#[inline(always)]
pub fn len(&self) -> usize {
self.repr.count_ones() as usize
}
/// Returns `true` if the set contains no elements.
#[inline(always)]
pub fn is_empty(&self) -> bool {
self.repr.is_empty()
}
/// Removes all elements from the set.
#[inline(always)]
pub fn clear(&mut self) {
self.repr = T::Repr::EMPTY;
}
/// Returns `true` if `self` has no elements in common with `other`. This is equivalent to
/// checking for an empty intersection.
#[inline(always)]
pub fn is_disjoint(&self, other: Self) -> bool {
(*self & other).is_empty()
}
/// Returns `true` if the set is a superset of another, i.e., `self` contains at least all the
/// values in `other`.
#[inline(always)]
pub fn is_superset(&self, other: Self) -> bool {
(*self & other).repr == other.repr
}
/// Returns `true` if the set is a subset of another, i.e., `other` contains at least all
/// the values in `self`.
#[inline(always)]
pub fn is_subset(&self, other: Self) -> bool {
other.is_superset(*self)
}
/// Returns a set containing any elements present in either set.
#[inline(always)]
pub fn union(&self, other: Self) -> Self {
EnumSet { repr: self.repr | other.repr }
}
/// Returns a set containing every element present in both sets.
#[inline(always)]
pub fn intersection(&self, other: Self) -> Self {
EnumSet { repr: self.repr & other.repr }
}
/// Returns a set containing element present in `self` but not in `other`.
#[inline(always)]
pub fn difference(&self, other: Self) -> Self {
EnumSet { repr: self.repr.and_not(other.repr) }
}
/// Returns a set containing every element present in either `self` or `other`, but is not
/// present in both.
#[inline(always)]
pub fn symmetrical_difference(&self, other: Self) -> Self {
EnumSet { repr: self.repr ^ other.repr }
}
/// Returns a set containing all enum variants not in this set.
#[inline(always)]
pub fn complement(&self) -> Self {
EnumSet { repr: !self.repr & T::ALL_BITS }
}
/// Checks whether this set contains a value.
#[inline(always)]
pub fn contains(&self, value: T) -> bool {
self.repr.has_bit(value.enum_into_u32())
}
/// Adds a value to this set.
///
/// If the set did not have this value present, `true` is returned.
///
/// If the set did have this value present, `false` is returned.
#[inline(always)]
pub fn insert(&mut self, value: T) -> bool {
let contains = !self.contains(value);
self.repr.add_bit(value.enum_into_u32());
contains
}
/// Removes a value from this set. Returns whether the value was present in the set.
#[inline(always)]
pub fn remove(&mut self, value: T) -> bool {
let contains = self.contains(value);
self.repr.remove_bit(value.enum_into_u32());
contains
}
/// Adds all elements in another set to this one.
#[inline(always)]
pub fn insert_all(&mut self, other: Self) {
self.repr = self.repr | other.repr
}
/// Removes all values in another set from this one.
#[inline(always)]
pub fn remove_all(&mut self, other: Self) {
self.repr = self.repr.and_not(other.repr);
}
}
/// A helper type used for constant evaluation of enum operations.
#[doc(hidden)]
pub struct EnumSetInitHelper;
impl EnumSetInitHelper {
/// Just returns this value - the version for the enums themselves would wrap it into an
/// enumset.
pub const fn const_only<T>(&self, value: T) -> T {
value
}
}
#[doc(hidden)]
unsafe impl<T: EnumSetType> EnumSetConstHelper for EnumSet<T> {
type ConstInitHelper = EnumSetInitHelper;
const CONST_INIT_HELPER: Self::ConstInitHelper = EnumSetInitHelper;
type ConstOpHelper = T::ConstOpHelper;
const CONST_OP_HELPER: Self::ConstOpHelper = T::CONST_OP_HELPER;
}
impl<T: EnumSetType> Default for EnumSet<T> {
/// Returns an empty set.
fn default() -> Self {
Self::new()
}
}
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> {
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> {
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> {
type Output = Self;
#[inline(always)]
fn bitxor(self, other: O) -> Self::Output {
self.symmetrical_difference(other.into())
}
}
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> {
#[inline(always)]
fn bitand_assign(&mut self, rhs: O) {
*self = *self & rhs;
}
}
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> {
#[inline(always)]
fn bitxor_assign(&mut self, rhs: O) {
*self = *self ^ rhs;
}
}
impl<T: EnumSetType> Not for EnumSet<T> {
type Output = Self;
#[inline(always)]
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.repr == EnumSet::only(*other).repr
}
}
impl<T: EnumSetType + Debug> Debug for EnumSet<T> {
fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
// Note: We don't use `.debug_struct` to avoid splitting lines when using `{:x}`
f.write_str("EnumSet(")?;
let mut i = self.iter();
if let Some(v) = i.next() {
v.fmt(f)?;
for v in i {
f.write_str(" | ")?;
v.fmt(f)?;
}
}
f.write_str(")")?;
Ok(())
}
}
impl<T: EnumSetType + Display> Display for EnumSet<T> {
fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
let mut i = self.iter();
if let Some(v) = i.next() {
v.fmt(f)?;
for v in i {
f.write_str(" | ")?;
v.fmt(f)?;
}
}
Ok(())
}
}
#[cfg(feature = "defmt")]
impl<T: EnumSetType + defmt::Format> defmt::Format for EnumSet<T> {
fn format(&self, f: defmt::Formatter) {
let mut i = self.iter();
if let Some(v) = i.next() {
defmt::write!(f, "{}", v);
for v in i {
defmt::write!(f, " | {}", v);
}
}
}
}
#[allow(clippy::derived_hash_with_manual_eq)] // This impl exists to change trait bounds only.
impl<T: EnumSetType> Hash for EnumSet<T> {
fn hash<H: Hasher>(&self, state: &mut H) {
self.repr.hash(state)
}
}
#[allow(clippy::non_canonical_partial_ord_impl)]
impl<T: EnumSetType> PartialOrd for EnumSet<T> {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
self.repr.partial_cmp(&other.repr)
}
}
impl<T: EnumSetType> Ord for EnumSet<T> {
fn cmp(&self, other: &Self) -> Ordering {
self.repr.cmp(&other.repr)
}
}
#[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)
}
}
//endregion
//region Deprecated functions
/// This impl contains all outdated or deprecated functions.
impl<T: EnumSetType> EnumSet<T> {
/// An empty `EnumSet`.
///
/// This is deprecated because [`EnumSet::empty`] is now `const`.
#[deprecated = "Use `EnumSet::empty()` instead."]
pub const EMPTY: Self = Self::EMPTY_REPR;
/// An `EnumSet` containing all valid variants of the enum.
///
/// This is deprecated because [`EnumSet::all`] is now `const`.
#[deprecated = "Use `EnumSet::all()` instead."]
pub const ALL: Self = Self::ALL_REPR;
}
//endregion
//region EnumSet conversions
impl<T: EnumSetType + EnumSetTypeWithRepr> EnumSet<T> {
/// Returns a `T::Repr` representing the elements of this set.
///
/// Unlike the other `as_*` methods, this method is zero-cost and guaranteed not to fail,
/// panic or truncate any bits.
///
/// In order to use this method, the definition of `T` must have an
/// [`#[enumset(repr = "…")]`](derive@crate::EnumSetType#representation-options) annotation
/// with a primitive integer type.
#[inline(always)]
pub const fn as_repr(&self) -> <T as EnumSetTypeWithRepr>::Repr {
self.repr
}
/// Constructs a bitset from a `T::Repr` without checking for invalid bits.
///
/// Unlike the other `from_*` methods, this method is zero-cost and guaranteed not to fail,
/// panic or truncate any bits, provided the conditions under “Safety” are upheld.
///
/// In order to use this method, the definition of `T` must have an
/// [`#[enumset(repr = "…")]`](derive@crate::EnumSetType#representation-options) annotation
/// with a primitive integer type.
///
/// # Safety
///
/// All bits in the provided parameter `bits` that don't correspond to an enum variant of
/// `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 {
Self { repr: bits }
}
/// Constructs a bitset from a `T::Repr`.
///
/// If a bit that doesn't correspond to an enum variant is set, this
/// method will panic.
///
/// In order to use this method, the definition of `T` must have an
/// [`#[enumset(repr = "…")]`](derive@crate::EnumSetType#representation-options) annotation
/// with a primitive integer type.
#[inline(always)]
pub fn from_repr(bits: <T as EnumSetTypeWithRepr>::Repr) -> Self {
Self::try_from_repr(bits).expect("Bitset contains invalid variants.")
}
/// Attempts to constructs a bitset from a `T::Repr`.
///
/// If a bit that doesn't correspond to an enum variant is set, this
/// method will return `None`.
///
/// In order to use this method, the definition of `T` must have an
/// [`#[enumset(repr = "…")]`](derive@crate::EnumSetType#representation-options) annotation
/// with a primitive integer type.
#[inline(always)]
pub fn try_from_repr(bits: <T as EnumSetTypeWithRepr>::Repr) -> Option<Self> {
let mask = Self::all().repr;
if bits.and_not(mask).is_empty() {
Some(EnumSet { repr: bits })
} else {
None
}
}
/// Constructs a bitset from a `T::Repr`, ignoring invalid variants.
///
/// In order to use this method, the definition of `T` must have an
/// [`#[enumset(repr = "…")]`](derive@crate::EnumSetType#representation-options) annotation
/// with a primitive integer type.
#[inline(always)]
pub fn from_repr_truncated(bits: <T as EnumSetTypeWithRepr>::Repr) -> Self {
let mask = Self::all().as_repr();
let bits = bits & mask;
EnumSet { repr: bits }
}
}
/// Helper macro for generating conversion functions.
macro_rules! conversion_impls {
(
$(for_num!(
$underlying:ty, $underlying_str:expr,
$from_fn:ident $to_fn:ident $from_fn_opt:ident $to_fn_opt:ident,
$from:ident $try_from:ident $from_truncated:ident $from_unchecked:ident,
$to:ident $try_to:ident $to_truncated:ident
);)*
) => {
impl<T: EnumSetType> EnumSet<T> {$(
#[doc = "Returns a `"]
#[doc = $underlying_str]
#[doc = "` representing the elements of this set.\n\nIf the underlying bitset will \
not fit in a `"]
#[doc = $underlying_str]
#[doc = "`, this method will panic."]
#[inline(always)]
pub fn $to(&self) -> $underlying {
self.$try_to().expect("Bitset will not fit into this type.")
}
#[doc = "Tries to return a `"]
#[doc = $underlying_str]
#[doc = "` representing the elements of this set.\n\nIf the underlying bitset will \
not fit in a `"]
#[doc = $underlying_str]
#[doc = "`, this method will panic."]
#[inline(always)]
pub fn $try_to(&self) -> Option<$underlying> {
EnumSetTypeRepr::$to_fn_opt(&self.repr)
}
#[doc = "Returns a truncated `"]
#[doc = $underlying_str]
#[doc = "` representing the elements of this set.\n\nIf the underlying bitset will \
not fit in a `"]
#[doc = $underlying_str]
#[doc = "`, this method will truncate any bits that don't fit."]
#[inline(always)]
pub fn $to_truncated(&self) -> $underlying {
EnumSetTypeRepr::$to_fn(&self.repr)
}
#[doc = "Constructs a bitset from a `"]
#[doc = $underlying_str]
#[doc = "`.\n\nIf a bit that doesn't correspond to an enum variant is set, this \
method will panic."]
#[inline(always)]
pub fn $from(bits: $underlying) -> Self {
Self::$try_from(bits).expect("Bitset contains invalid variants.")
}
#[doc = "Attempts to constructs a bitset from a `"]
#[doc = $underlying_str]
#[doc = "`.\n\nIf a bit that doesn't correspond to an enum variant is set, this \
method will return `None`."]
#[inline(always)]
pub fn $try_from(bits: $underlying) -> Option<Self> {
let bits = T::Repr::$from_fn_opt(bits);
let mask = T::ALL_BITS;
bits.and_then(|bits| if bits.and_not(mask).is_empty() {
Some(EnumSet { repr: bits })
} else {
None
})
}
#[doc = "Constructs a bitset from a `"]
#[doc = $underlying_str]
#[doc = "`, ignoring bits that do not correspond to a variant."]
#[inline(always)]
pub fn $from_truncated(bits: $underlying) -> Self {
let mask = Self::all().$to_truncated();
let bits = <T::Repr as EnumSetTypeRepr>::$from_fn(bits & mask);
EnumSet { repr: bits }
}
#[doc = "Constructs a bitset from a `"]
#[doc = $underlying_str]
#[doc = "`, without checking for invalid bits."]
///
/// # Safety
///
/// All bits in the provided parameter `bits` that don't correspond to an enum variant
/// of `T` must be set to `0`. Behavior is **undefined** if any of these bits are set
/// to `1`.
#[inline(always)]
pub unsafe fn $from_unchecked(bits: $underlying) -> Self {
EnumSet { repr: <T::Repr as EnumSetTypeRepr>::$from_fn(bits) }
}
)*}
}
}
conversion_impls! {
for_num!(u8, "u8",
from_u8 to_u8 from_u8_opt to_u8_opt,
from_u8 try_from_u8 from_u8_truncated from_u8_unchecked,
as_u8 try_as_u8 as_u8_truncated);
for_num!(u16, "u16",
from_u16 to_u16 from_u16_opt to_u16_opt,
from_u16 try_from_u16 from_u16_truncated from_u16_unchecked,
as_u16 try_as_u16 as_u16_truncated);
for_num!(u32, "u32",
from_u32 to_u32 from_u32_opt to_u32_opt,
from_u32 try_from_u32 from_u32_truncated from_u32_unchecked,
as_u32 try_as_u32 as_u32_truncated);
for_num!(u64, "u64",
from_u64 to_u64 from_u64_opt to_u64_opt,
from_u64 try_from_u64 from_u64_truncated from_u64_unchecked,
as_u64 try_as_u64 as_u64_truncated);
for_num!(u128, "u128",
from_u128 to_u128 from_u128_opt to_u128_opt,
from_u128 try_from_u128 from_u128_truncated from_u128_unchecked,
as_u128 try_as_u128 as_u128_truncated);
for_num!(usize, "usize",
from_usize to_usize from_usize_opt to_usize_opt,
from_usize try_from_usize from_usize_truncated from_usize_unchecked,
as_usize try_as_usize as_usize_truncated);
}
impl<T: EnumSetType> EnumSet<T> {
/// Returns an `[u64; O]` representing the elements of this set.
///
/// If the underlying bitset will not fit in a `[u64; O]`, this method will panic.
pub fn as_array<const O: usize>(&self) -> [u64; O] {
self.try_as_array()
.expect("Bitset will not fit into this type.")
}
/// Returns an `[u64; O]` representing the elements of this set.
///
/// If the underlying bitset will not fit in a `[u64; O]`, this method will instead return
/// `None`.
pub fn try_as_array<const O: usize>(&self) -> Option<[u64; O]> {
self.repr.to_u64_array_opt()
}
/// Returns an `[u64; O]` representing the elements of this set.
///
/// If the underlying bitset will not fit in a `[u64; O]`, this method will truncate any bits
/// that don't fit.
pub fn as_array_truncated<const O: usize>(&self) -> [u64; O] {
self.repr.to_u64_array()
}
/// Attempts to constructs a bitset from a `[u64; O]`.
///
/// If a bit that doesn't correspond to an enum variant is set, this method will panic.
pub fn from_array<const O: usize>(v: [u64; O]) -> Self {
Self::try_from_array(v).expect("Bitset contains invalid variants.")
}
/// Attempts to constructs a bitset from a `[u64; O]`.
///
/// If a bit that doesn't correspond to an enum variant is set, this method will return `None`.
pub fn try_from_array<const O: usize>(bits: [u64; O]) -> Option<Self> {
let bits = T::Repr::from_u64_array_opt::<O>(bits);
let mask = T::ALL_BITS;
bits.and_then(|bits| {
if bits.and_not(mask).is_empty() {
Some(EnumSet { repr: bits })
} else {
None
}
})
}
/// Constructs a bitset from a `[u64; O]`, ignoring bits that do not correspond to a variant.
pub fn from_array_truncated<const O: usize>(bits: [u64; O]) -> Self {
let bits = T::Repr::from_u64_array(bits) & T::ALL_BITS;
EnumSet { repr: bits }
}
/// Constructs a bitset from a `[u64; O]`, without checking for invalid bits.
///
/// # Safety
///
/// All bits in the provided parameter `bits` that don't correspond to an enum variant
/// of `T` must be set to `0`. Behavior is **undefined** if any of these bits are set
/// to `1`.
#[inline(always)]
pub unsafe fn from_array_unchecked<const O: usize>(bits: [u64; O]) -> Self {
EnumSet { repr: T::Repr::from_u64_array(bits) }
}
/// Returns a `Vec<u64>` representing the elements of this set.
#[cfg(feature = "alloc")]
#[cfg_attr(docsrs, doc(cfg(feature = "alloc")))]
pub fn to_vec(&self) -> alloc::vec::Vec<u64> {
let mut vec = alloc::vec![0; T::Repr::PREFERRED_ARRAY_LEN];
self.repr.to_u64_slice(&mut vec);
vec
}
/// Copies the elements of this set into a `&mut [u64]`.
///
/// If the underlying bitset will not fit in the provided slice, this method will panic.
pub fn copy_into_slice(&self, data: &mut [u64]) {
self.try_copy_into_slice(data)
.expect("Bitset will not fit into slice.")
}
/// Copies the elements of this set into a `&mut [u64]`.
///
/// If the underlying bitset will not fit in the provided slice, this method will return
/// `None`. Otherwise, it will return `Some(())`.
#[must_use]
pub fn try_copy_into_slice(&self, data: &mut [u64]) -> Option<()> {
self.repr.to_u64_slice_opt(data)
}
/// Copies the elements of this set into a `&mut [u64]`.
///
/// If the underlying bitset will not fit in the provided slice, this method will truncate any
/// bits that don't fit.
pub fn copy_into_slice_truncated(&self, data: &mut [u64]) {
self.repr.to_u64_slice(data)
}
/// Attempts to constructs a bitset from a `&[u64]`.
///
/// If a bit that doesn't correspond to an enum variant is set, this method will panic.
pub fn from_slice(v: &[u64]) -> Self {
Self::try_from_slice(v).expect("Bitset contains invalid variants.")
}
/// Attempts to constructs a bitset from a `&[u64]`.
///
/// If a bit that doesn't correspond to an enum variant is set, this method will return `None`.
pub fn try_from_slice(bits: &[u64]) -> Option<Self> {
let bits = T::Repr::from_u64_slice_opt(bits);
let mask = T::ALL_BITS;
bits.and_then(|bits| {
if bits.and_not(mask).is_empty() {
Some(EnumSet { repr: bits })
} else {
None
}
})
}
/// Constructs a bitset from a `&[u64]`, ignoring bits that do not correspond to a variant.
pub fn from_slice_truncated(bits: &[u64]) -> Self {
let bits = T::Repr::from_u64_slice(bits) & T::ALL_BITS;
EnumSet { repr: bits }
}
/// Constructs a bitset from a `&[u64]`, without checking for invalid bits.
///
/// # Safety
///
/// All bits in the provided parameter `bits` that don't correspond to an enum variant
/// of `T` must be set to `0`. Behavior is **undefined** if any of these bits are set
/// to `1`.
#[inline(always)]
pub unsafe fn from_slice_unchecked(bits: &[u64]) -> Self {
EnumSet { repr: T::Repr::from_u64_slice(bits) }
}
}
impl<T: EnumSetType, const N: usize> From<[T; N]> for EnumSet<T> {
fn from(value: [T; N]) -> Self {
let mut new = EnumSet::new();
for elem in value {
new.insert(elem);
}
new
}
}
//endregion
//region EnumSet iter
/// The iterator used by [`EnumSet`]s.
#[derive(Clone, Debug)]
pub struct EnumSetIter<T: EnumSetType> {
iter: <T::Repr as EnumSetTypeRepr>::Iter,
}
impl<T: EnumSetType> EnumSetIter<T> {
fn new(set: EnumSet<T>) -> EnumSetIter<T> {
EnumSetIter { iter: set.repr.iter() }
}
}
impl<T: EnumSetType> EnumSet<T> {
/// Iterates the contents of the set in order from the least significant bit to the most
/// significant bit.
///
/// Note that iterator invalidation is impossible as the iterator contains a copy of this type,
/// rather than holding a reference to it.
pub fn iter(&self) -> EnumSetIter<T> {
EnumSetIter::new(*self)
}
}
impl<T: EnumSetType> Iterator for EnumSetIter<T> {
type Item = T;
fn next(&mut self) -> Option<Self::Item> {
self.iter
.next()
.map(|x| unsafe { T::enum_from_u32_checked(x) })
}
fn size_hint(&self) -> (usize, Option<usize>) {
self.iter.size_hint()
}
}
impl<T: EnumSetType> DoubleEndedIterator for EnumSetIter<T> {
fn next_back(&mut self) -> Option<Self::Item> {
self.iter
.next_back()
.map(|x| unsafe { T::enum_from_u32_checked(x) })
}
}
impl<T: EnumSetType> ExactSizeIterator for EnumSetIter<T> {}
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<'a, T: EnumSetType> Extend<&'a T> for EnumSet<T> {
fn extend<I: IntoIterator<Item = &'a 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
}
}
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);
});
}
}
impl<'a, T: EnumSetType> Extend<&'a EnumSet<T>> for EnumSet<T> {
fn extend<I: IntoIterator<Item = &'a EnumSet<T>>>(&mut self, iter: I) {
iter.into_iter().for_each(|v| {
self.insert_all(*v);
});
}
}
impl<T: EnumSetType> FromIterator<EnumSet<T>> for EnumSet<T> {
fn from_iter<I: IntoIterator<Item = EnumSet<T>>>(iter: I) -> Self {
let mut set = EnumSet::default();
set.extend(iter);
set
}
}
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> 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 {
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 {
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 {
iter.fold(EnumSet::empty(), |a, v| a | *v)
}
}
//endregion
+82
View File
@@ -0,0 +1,82 @@
use crate::repr::EnumSetTypeRepr;
#[cfg(feature = "serde")]
use crate::EnumSet;
/// The trait used to define enum types that may be used with [`EnumSet`].
///
/// This trait must be impelmented using `#[derive(EnumSetType)]`, is not public API, and its
/// internal structure may change at any time with no warning.
///
/// For full documentation on the procedural derive and its options, see
/// [`#[derive(EnumSetType)]`](derive@crate::EnumSetType).
///
/// [`EnumSet`]: crate::set::EnumSet
pub unsafe trait EnumSetType: Copy + Eq + EnumSetTypePrivate {}
/// An [`EnumSetType`] for which [`EnumSet`]s have a guaranteed in-memory representation.
///
/// An implementation of this trait is generated by using
/// [`#[derive(EnumSetType)]`](derive@crate::EnumSetType) with the annotation
/// `#[enumset(repr = "…")]`, where `…` is `u8`, `u16`, `u32`, `u64` or `u128`.
///
/// 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`”][crate::set::EnumSet#ffi-safety-and-repr] for an example.
///
/// [`EnumSet`]: crate::set::EnumSet
pub unsafe trait EnumSetTypeWithRepr:
EnumSetType + EnumSetTypePrivate<Repr = <Self as EnumSetTypeWithRepr>::Repr>
{
/// The guaranteed representation.
type Repr: EnumSetTypeRepr;
}
/// The actual members of EnumSetType. Put here to avoid polluting global namespaces.
pub unsafe trait EnumSetTypePrivate: EnumSetConstHelper + Sized {
/// The underlying type used to store the bitset.
type Repr: EnumSetTypeRepr;
/// A mask of bits that are valid in the bitset.
const ALL_BITS: Self::Repr;
/// The largest bit used in the bitset.
const BIT_WIDTH: u32;
/// The number of variants in the bitset.
const VARIANT_COUNT: u32;
/// Converts an enum of this type into its bit position.
fn enum_into_u32(self) -> u32;
/// Converts a bit position into an enum value.
unsafe fn enum_from_u32(val: u32) -> Self;
/// Converts a bit position into an enum value, with an debug_assert.
unsafe fn enum_from_u32_checked(val: u32) -> Self {
debug_assert!(Self::ALL_BITS.has_bit(val), "Unknown bit retrieved from bitset.");
Self::enum_from_u32(val)
}
/// Serializes the `EnumSet`.
///
/// This and `deserialize` are part of the `EnumSetType` trait so the procedural derive
/// 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;
/// Deserializes the `EnumSet`.
#[cfg(feature = "serde")]
fn deserialize<'de, D: serde::Deserializer<'de>>(de: D) -> Result<EnumSet<Self>, D::Error>
where Self: EnumSetType;
}
/// Retrieves a helper type for constant time operations on `EnumSet`s.
pub unsafe trait EnumSetConstHelper {
/// A helper type used to convert values to EnumSets at compile-time.
type ConstInitHelper;
/// The instance of the `ConstInitHelper`.
const CONST_INIT_HELPER: Self::ConstInitHelper;
/// A helper type used to implement compile-time operations on enums.
type ConstOpHelper;
/// The instance of the `ConstOpHelper`.
const CONST_OP_HELPER: Self::ConstOpHelper;
}