Skip to main content

Enumerable

Trait Enumerable 

Source
pub unsafe trait Enumerable: Copy + 'static {
    const VARIANTS: &'static [Self];
    const COUNT: usize = _;

    // Provided method
    fn variant_index(&self) -> usize { ... }
}
Expand description

A Copy enum whose variants EnumTable can enumerate and index by position.

Prefer #[derive(Enumerable)] over a hand-written unsafe impl; it upholds the safety contract below automatically for field-less enums.

§Safety

Self must have no padding bytes: the default Self::variant_index and every EnumTable constructor compare Self by reading it as raw bytes, and padding bytes may be uninitialized memory.

VARIANTS must list every variant of Self exactly once, sorted ascending by the unsigned bit-pattern of its representation (e.g. under #[repr(i8)], -1 sorts after 0 and 1, since its bit pattern 0xFF is the larger one). Getting this wrong is not itself undefined behavior - indexing stays bounds-checked - but makes EnumTable::get/set/etc. return or mutate the wrong variant’s value. Every EnumTable constructor asserts this ordering at compile time.

§Examples

use enum_table::Enumerable;

#[derive(Copy, Clone)]
#[repr(u8)]
enum Test {
    A,
    B,
    C,
}

// SAFETY: `Test` is a field-less `#[repr(u8)]` enum (no padding bytes),
// and `VARIANTS` lists every variant exactly once, sorted by discriminant.
unsafe impl Enumerable for Test {
    const VARIANTS: &'static [Self] = &[Test::A, Test::B, Test::C];
}

assert_eq!(Test::B.variant_index(), 1);

Required Associated Constants§

Source

const VARIANTS: &'static [Self]

Provided Associated Constants§

Source

const COUNT: usize = _

Provided Methods§

Source

fn variant_index(&self) -> usize

Returns the index of this variant within Self::VARIANTS.

The default implementation runs an O(log N) binary search; #[derive(Enumerable)] overrides it with a compile-time match.

Dyn Compatibility§

This trait is not dyn compatible.

In older versions of Rust, dyn compatibility was called "object safety".

Implementors§