Struct EnumTable

Source
pub struct EnumTable<K: Enumable, V, const N: usize> { /* private fields */ }
Expand description

A table that associates each variant of an enumeration with a value.

EnumTable is a generic struct that uses an enumeration as keys and stores associated values. It provides constant-time access to the values based on the enumeration variant. This is particularly useful when you want to map enum variants to specific values without the overhead of a HashMap.

§Type Parameters

  • K: The enumeration type that implements the Enumable trait. This trait ensures that the enum provides a static array of its variants and a count of these variants.
  • V: The type of values to be associated with each enum variant.
  • N: The number of variants in the enum, which should match the length of the static array of variants provided by the Enumable trait.

§Note

The new method allows for the creation of an EnumTable in const contexts, but it does not perform compile-time checks. For enhanced compile-time safety and convenience, it is advisable to use the crate::et macro or crate::builder::EnumTableBuilder, which provide these checks.

§Examples

use enum_table::{EnumTable, Enumable};

#[derive(Enumable)]
enum Color {
    Red,
    Green,
    Blue,
}

// Create an EnumTable using the new_with_fn method
let table = EnumTable::<Color, &'static str, { Color::COUNT }>::new_with_fn(|color| match color {
    Color::Red => "Red",
    Color::Green => "Green",
    Color::Blue => "Blue",
});

// Access values associated with enum variants
assert_eq!(table.get(&Color::Red), &"Red");
assert_eq!(table.get(&Color::Green), &"Green");
assert_eq!(table.get(&Color::Blue), &"Blue");

Implementations§

Source§

impl<K: Enumable, V, const N: usize> EnumTable<K, V, N>

Source

pub const fn new(table: [(usize, V); N]) -> Self

Creates a new EnumTable with the given table of discriminants and values. Typically, you would use the crate::et macro or the crate::builder::EnumTableBuilder instead.

§Arguments
  • table - An array of tuples where each tuple contains a discriminant of an enumeration variant and its associated value.
Source

pub fn new_with_fn(f: impl FnMut(&K) -> V) -> Self

Create a new EnumTable with a function that takes a variant and returns a value. If you want to define it in const, use crate::et macro Creates a new EnumTable using a function to generate values for each variant.

§Arguments
  • f - A function that takes a reference to an enumeration variant and returns a value to be associated with that variant.
Source

pub fn try_new_with_fn<E>( f: impl FnMut(&K) -> Result<V, E>, ) -> Result<Self, (&'static K, E)>

Creates a new EnumTable using a function that returns a Result for each variant.

This method applies the provided closure to each variant of the enum. If the closure returns Ok(value) for all variants, an EnumTable is constructed and returned as Ok(Self). If the closure returns Err(e) for any variant, the construction is aborted and Err((variant, e)) is returned, where variant is the enum variant that caused the error.

§Arguments
  • f - A closure that takes a reference to an enum variant and returns a Result<V, E>.
§Returns
  • Ok(Self) if all variants succeed.
  • Err((variant, e)) if any variant fails, containing the failing variant and the error.
Source

pub fn checked_new_with_fn( f: impl FnMut(&K) -> Option<V>, ) -> Result<Self, &'static K>

Creates a new EnumTable using a function that returns an Option for each variant.

This method applies the provided closure to each variant of the enum. If the closure returns Some(value) for all variants, an EnumTable is constructed and returned as Ok(Self). If the closure returns None for any variant, the construction is aborted and Err(variant) is returned, where variant is the enum variant that caused the failure.

§Arguments
  • f - A closure that takes a reference to an enum variant and returns an Option<V>.
§Returns
  • Ok(Self) if all variants succeed.
  • Err(variant) if any variant fails, containing the failing variant.
Source

pub const fn get(&self, variant: &K) -> &V

Returns a reference to the value associated with the given enumeration variant.

§Arguments
  • variant - A reference to an enumeration variant.
Source

pub const fn get_mut(&mut self, variant: &K) -> &mut V

Returns a mutable reference to the value associated with the given enumeration variant.

§Arguments
  • variant - A reference to an enumeration variant.
Source

pub const fn set(&mut self, variant: &K, value: V) -> V

Sets the value associated with the given enumeration variant.

§Arguments
  • variant - A reference to an enumeration variant.
  • value - The new value to associate with the variant.
§Returns

The old value associated with the variant.

Source

pub const fn len(&self) -> usize

Returns the number of generic N

Source

pub const fn is_empty(&self) -> bool

Returns false since the table is never empty.

Source

pub fn keys(&self) -> impl Iterator<Item = &K>

Returns an iterator over references to the keys in the table.

Source

pub fn values(&self) -> impl Iterator<Item = &V>

Returns an iterator over references to the values in the table.

Source

pub fn values_mut(&mut self) -> impl Iterator<Item = &mut V>

Returns an iterator over mutable references to the values in the table.

Source

pub fn iter(&self) -> impl Iterator<Item = (&K, &V)>

Returns an iterator over mutable references to the values in the table.

Source

pub fn iter_mut(&mut self) -> impl Iterator<Item = (&K, &mut V)>

Returns an iterator over mutable references to the values in the table.

Trait Implementations§

Source§

impl<K: Enumable, V: Clone, const N: usize> Clone for EnumTable<K, V, N>

Source§

fn clone(&self) -> Self

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl<K: Enumable + Debug, V: Debug, const N: usize> Debug for EnumTable<K, V, N>

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl<K: Enumable, V: Default, const N: usize> Default for EnumTable<K, V, N>

Source§

fn default() -> Self

Returns the “default value” for a type. Read more
Source§

impl<K: Enumable, V: Hash, const N: usize> Hash for EnumTable<K, V, N>

Source§

fn hash<H: Hasher>(&self, state: &mut H)

Feeds this value into the given Hasher. Read more
1.3.0 · Source§

fn hash_slice<H>(data: &[Self], state: &mut H)
where H: Hasher, Self: Sized,

Feeds a slice of this type into the given Hasher. Read more
Source§

impl<K: Enumable, V, const N: usize> Index<K> for EnumTable<K, V, N>

Source§

type Output = V

The returned type after indexing.
Source§

fn index(&self, index: K) -> &Self::Output

Performs the indexing (container[index]) operation. Read more
Source§

impl<K: Enumable, V, const N: usize> IndexMut<K> for EnumTable<K, V, N>

Source§

fn index_mut(&mut self, index: K) -> &mut Self::Output

Performs the mutable indexing (container[index]) operation. Read more
Source§

impl<K: Enumable, V: PartialEq, const N: usize> PartialEq for EnumTable<K, V, N>

Source§

fn eq(&self, other: &Self) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

impl<K: Enumable, V: Eq, const N: usize> Eq for EnumTable<K, V, N>

Auto Trait Implementations§

§

impl<K, V, const N: usize> Freeze for EnumTable<K, V, N>
where V: Freeze,

§

impl<K, V, const N: usize> RefUnwindSafe for EnumTable<K, V, N>

§

impl<K, V, const N: usize> Send for EnumTable<K, V, N>
where K: Send, V: Send,

§

impl<K, V, const N: usize> Sync for EnumTable<K, V, N>
where K: Sync, V: Sync,

§

impl<K, V, const N: usize> Unpin for EnumTable<K, V, N>
where K: Unpin, V: Unpin,

§

impl<K, V, const N: usize> UnwindSafe for EnumTable<K, V, N>
where K: UnwindSafe, V: UnwindSafe,

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.