Crate cenum_utils

Source
Expand description

githubcrates-iodocs-rs

cenum_utils provides a minimal set of traits and (optionally) derive macros providing const access to certain enum properties.

Currently this includes:

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§

EnumCount
A trait providing access to the number of enum variants a type contains.
EnumDiscriminants
A trait providing access to the discriminants of an enum’s variants.
EnumNames
A trait providing access to the names of an enum’s variants.

Derive Macros§

ConstEnumderive
Derives EnumCount and EnumNames, as well as EnumDiscriminants if the enum has a valid primitive repr type.