Expand description
cenum_utils
provides a minimal set of traits and (optionally) derive macros providing const access to certain enum properties.
Currently this includes:
- EnumCount — Variant counts.
- EnumDiscriminants — Variant discriminants.
- EnumNames — Variant names.
Unfortunately, due to rust’s currently lack of const trait support, actually interacting with some of the features this crate provides in const contexts can be somewhat difficult.
§Example
use cenum_utils::*;
#[derive(ConstEnum)]
#[repr(u8)]
enum Enum {
X,
Y,
Z
}
fn test() {
assert_eq!(Enum::COUNT, 3);
assert_eq!(Enum::DISCRIMINANTS, &[0, 1, 2]);
assert_eq!(Enum::NAMES, &["X", "Y", "Z"])
}
const fn const_test() {
assert!(Enum::COUNT == 3);
static NAMES: &[u8] = &[b'X', b'Y', b'Z'];
let mut i = 0;
while i < Enum::COUNT {
assert!(Enum::DISCRIMINANTS[i] as usize == i);
assert!(Enum::NAMES[i].as_bytes()[0] == NAMES[i]);
i += 1;
}
}
§Features
derive
(enabled by default) — Derive macros for the core traits provided by this crate.
Traits§
- Enum
Count - A trait providing access to the number of enum variants a type contains.
- Enum
Discriminants - A trait providing access to the discriminants of an enum’s variants.
- Enum
Names - A trait providing access to the names of an enum’s variants.
Derive Macros§
- Const
Enum derive
- Derives
EnumCount
andEnumNames
, as well asEnumDiscriminants
if the enum has a valid primitiverepr
type.