enumset/
traits.rs

1use crate::repr::EnumSetTypeRepr;
2
3#[cfg(feature = "serde")]
4use {crate::EnumSet, serde2 as serde};
5
6/// The trait used to define enum types that may be used with [`EnumSet`].
7///
8/// This trait must be impelmented using `#[derive(EnumSetType)]`, is not public API, and its
9/// internal structure may change at any time with no warning.
10///
11/// For full documentation on the procedural derive and its options, see
12/// [`#[derive(EnumSetType)]`](derive@crate::EnumSetType).
13///
14/// [`EnumSet`]: crate::set::EnumSet
15pub unsafe trait EnumSetType: Copy + Eq + EnumSetTypePrivate {}
16
17/// An [`EnumSetType`] for which [`EnumSet`]s have a guaranteed in-memory representation.
18///
19/// An implementation of this trait is generated by using
20/// [`#[derive(EnumSetType)]`](derive@crate::EnumSetType) with the annotation
21/// `#[enumset(repr = "…")]`, where `…` is `u8`, `u16`, `u32`, `u64` or `u128`.
22///
23/// For any type `T` that implements this trait, the in-memory representation of `EnumSet<T>`
24/// is guaranteed to be `Repr`. This guarantee is useful for FFI. See [the `EnumSet` documentation
25/// under “FFI, Safety and `repr`”][crate::set::EnumSet#ffi-safety-and-repr] for an example.
26///
27/// [`EnumSet`]: crate::set::EnumSet
28pub unsafe trait EnumSetTypeWithRepr:
29    EnumSetType + EnumSetTypePrivate<Repr = <Self as EnumSetTypeWithRepr>::Repr>
30{
31    /// The guaranteed representation.
32    type Repr: EnumSetTypeRepr;
33}
34
35/// The actual members of EnumSetType. Put here to avoid polluting global namespaces.
36pub unsafe trait EnumSetTypePrivate {
37    /// A helper type used to implement the `enum_set!` macro among other things.
38    type ConstHelper;
39    /// The instance of the `ConstHelper`.
40    const CONST_HELPER_INSTANCE: Self::ConstHelper;
41
42    /// The underlying type used to store the bitset.
43    type Repr: EnumSetTypeRepr;
44    /// A mask of bits that are valid in the bitset.
45    const ALL_BITS: Self::Repr;
46    /// The largest bit used in the bitset.
47    const BIT_WIDTH: u32;
48    /// The number of variants in the bitset.
49    const VARIANT_COUNT: u32;
50
51    /// Converts an enum of this type into its bit position.
52    fn enum_into_u32(self) -> u32;
53    /// Converts a bit position into an enum value.
54    unsafe fn enum_from_u32(val: u32) -> Self;
55
56    /// Serializes the `EnumSet`.
57    ///
58    /// This and `deserialize` are part of the `EnumSetType` trait so the procedural derive
59    /// can control how `EnumSet` is serialized.
60    #[cfg(feature = "serde")]
61    fn serialize<S: serde::Serializer>(set: EnumSet<Self>, ser: S) -> Result<S::Ok, S::Error>
62    where Self: EnumSetType;
63    /// Deserializes the `EnumSet`.
64    #[cfg(feature = "serde")]
65    fn deserialize<'de, D: serde::Deserializer<'de>>(de: D) -> Result<EnumSet<Self>, D::Error>
66    where Self: EnumSetType;
67}