Debian Codegraph @

third_party/rust/enumset/src/traits.rs

raw
1 use crate::repr::EnumSetTypeRepr;
2
3 #[cfg(feature = "serde")]
4 use {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
15 pub 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
28 pub 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.
36 pub unsafe trait EnumSetTypePrivate {
37 /// The underlying type used to store the bitset.
38 type Repr: EnumSetTypeRepr;
39 /// A mask of bits that are valid in the bitset.
40 const ALL_BITS: Self::Repr;
41 /// The largest bit used in the bitset.
42 const BIT_WIDTH: u32;
43 /// The number of variants in the bitset.
44 const VARIANT_COUNT: u32;
45
46 /// Converts an enum of this type into its bit position.
47 fn enum_into_u32(self) -> u32;
48 /// Converts a bit position into an enum value.
49 unsafe fn enum_from_u32(val: u32) -> Self;
50
51 /// Serializes the `EnumSet`.
52 ///
53 /// This and `deserialize` are part of the `EnumSetType` trait so the procedural derive
54 /// can control how `EnumSet` is serialized.
55 #[cfg(feature = "serde")]
56 fn serialize<S: serde::Serializer>(set: EnumSet<Self>, ser: S) -> Result<S::Ok, S::Error>
57 where Self: EnumSetType;
58 /// Deserializes the `EnumSet`.
59 #[cfg(feature = "serde")]
60 fn deserialize<'de, D: serde::Deserializer<'de>>(de: D) -> Result<EnumSet<Self>, D::Error>
61 where Self: EnumSetType;
62 }