enum_ordinalize/traits.rs
1/// This trait provides an enum with the ability to not only obtain the ordinal values of its variants but also allows for the construction of enums from an ordinal value.
2///
3/// ```rust
4/// use enum_ordinalize::Ordinalize;
5///
6/// #[repr(u8)]
7/// enum E {
8/// A,
9/// B,
10/// }
11///
12/// impl Ordinalize for E {
13/// type VariantType = u8;
14///
15/// const VALUES: &'static [Self::VariantType] = &[0, 1];
16/// const VARIANTS: &'static [Self] = &[E::A, E::B];
17/// const VARIANT_COUNT: usize = 2;
18///
19/// #[inline]
20/// unsafe fn from_ordinal_unsafe(number: Self::VariantType) -> Self {
21/// ::core::mem::transmute(number)
22/// }
23///
24/// #[inline]
25/// fn from_ordinal(number: Self::VariantType) -> Option<Self> {
26/// match number {
27/// 0 => Some(Self::A),
28/// 1 => Some(Self::B),
29/// _ => None,
30/// }
31/// }
32///
33/// #[inline]
34/// fn ordinal(&self) -> Self::VariantType {
35/// match self {
36/// Self::A => 0,
37/// Self::B => 1,
38/// }
39/// }
40/// }
41/// ```
42pub trait Ordinalize: Sized + 'static {
43 /// The type of the values of the variants.
44 type VariantType;
45
46 /// The count of variants.
47 const VARIANT_COUNT: usize;
48
49 /// List of this enum's variants.
50 const VARIANTS: &'static [Self];
51
52 /// List of values for all variants of this enum.
53 const VALUES: &'static [Self::VariantType];
54
55 /// Obtain a variant based on an integer number.
56 ///
57 /// # Safety
58 /// You have to ensure that the input integer number can correspond to a variant on your own.
59 unsafe fn from_ordinal_unsafe(number: Self::VariantType) -> Self;
60
61 /// Obtain a variant based on an integer number.
62 fn from_ordinal(number: Self::VariantType) -> Option<Self>
63 where
64 Self: Sized;
65
66 /// Retrieve the integer number of this variant.
67 fn ordinal(&self) -> Self::VariantType;
68}