Skip to main content

EnumTable

Struct EnumTable 

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

A fixed-size table holding one V per variant of K.

A value always exists for every variant, so Self::get returns &V directly rather than Option<&V>; use EnumTable<K, Option<V>, N> to allow an absent value.

§Examples

use enum_table::{EnumTable, Enumerable};

#[derive(Enumerable, Copy, Clone)]
enum Color {
    Red,
    Green,
    Blue,
}

let table = EnumTable::<Color, &'static str, { Color::COUNT }>::from_fn(|color| match color {
    Color::Red => "Red",
    Color::Green => "Green",
    Color::Blue => "Blue",
});

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: Enumerable, V, const N: usize> EnumTable<K, V, N>

Source

pub fn keys(&self) -> Iter<'_, K>

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

Source

pub fn values(&self) -> Iter<'_, V>

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

Source

pub fn values_mut(&mut self) -> IterMut<'_, 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 references to the key-value pairs in the table.

Source

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

Returns an iterator over mutable references to the key-value pairs in the table.

Source§

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

Source

pub fn checked_from_pairs( pairs: impl IntoIterator<Item = (K, V), IntoIter: ExactSizeIterator>, ) -> Option<Self>

Creates a new EnumTable from pairs, or returns None if pairs doesn’t contain exactly one entry for each variant of K.

§Examples
use enum_table::{EnumTable, Enumerable};

#[derive(Enumerable, Copy, Clone, Debug, PartialEq)]
enum Color {
    Red,
    Green,
    Blue,
}

let pairs = [
    (Color::Red, "Red"),
    (Color::Green, "Green"),
    (Color::Blue, "Blue"),
];
let table = EnumTable::<Color, &str, { Color::COUNT }>::checked_from_pairs(pairs).unwrap();
assert_eq!(table.get(Color::Red), &"Red");
assert_eq!(table.get(Color::Green), &"Green");
assert_eq!(table.get(Color::Blue), &"Blue");

A duplicate entry is rejected, instead of silently producing a table with an unrelated variant missing:

use enum_table::{EnumTable, Enumerable};

#[derive(Enumerable, Copy, Clone, Debug, PartialEq)]
enum Color {
    Red,
    Green,
    Blue,
}

let pairs = [
    (Color::Red, "Red"),
    (Color::Green, "Green"),
    (Color::Red, "Duplicate Red"),
];
assert_eq!(
    EnumTable::<Color, &str, { Color::COUNT }>::checked_from_pairs(pairs),
    None
);
Source§

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

Source

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

Creates a new EnumTable by applying f to each variant of K.

Source

pub fn try_from_fn<E>(f: impl FnMut(K) -> Result<V, E>) -> Result<Self, E>

Creates a new EnumTable by applying f to each variant of K, stopping at the first Err.

§Examples
use enum_table::{EnumTable, Enumerable};

#[derive(Enumerable, Copy, Clone, Debug, PartialEq)]
enum Color {
    Red,
    Green,
    Blue,
}

let result = EnumTable::<Color, &'static str, { Color::COUNT }>::try_from_fn(
    |color| match color {
        Color::Red => Ok("Red"),
        Color::Green => Err("Failed to get value for Green"),
        Color::Blue => Ok("Blue"),
    },
);

assert_eq!(result, Err("Failed to get value for Green"));
Source

pub fn checked_from_fn(f: impl FnMut(K) -> Option<V>) -> Option<Self>

Creates a new EnumTable by applying f to each variant of K, stopping at the first None.

§Examples
use enum_table::{EnumTable, Enumerable};

#[derive(Enumerable, Copy, Clone)]
enum Color {
    Red,
    Green,
    Blue,
}

let table = EnumTable::<Color, &'static str, { Color::COUNT }>::checked_from_fn(
    |color| match color {
        Color::Red => Some("Red"),
        Color::Green => None,
        Color::Blue => Some("Blue"),
    },
);

assert!(table.is_none());
Source

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

Returns a reference to the value associated with variant.

Source

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

Returns a mutable reference to the value associated with variant.

Source

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

Replaces the value associated with variant, returning the previous value.

Source

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

const fn equivalent of Self::get.

Source

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

const fn equivalent of Self::get_mut.

Source

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

const fn equivalent of Self::set.

Source

pub fn zip_with<U, W>( self, other: EnumTable<K, U, N>, f: impl FnMut(K, V, U) -> W, ) -> EnumTable<K, W, N>

Combines self and other into a new table by applying f to each variant and its two values.

§Examples
use enum_table::{EnumTable, Enumerable};

#[derive(Enumerable, Copy, Clone)]
enum Stat {
    Hp,
    Attack,
    Defense,
}

let base = EnumTable::<Stat, i32, { Stat::COUNT }>::from_fn(|s| match s {
    Stat::Hp => 100,
    Stat::Attack => 50,
    Stat::Defense => 30,
});
let bonus = EnumTable::<Stat, i32, { Stat::COUNT }>::from_fn(|s| match s {
    Stat::Hp => 20,
    Stat::Attack => 10,
    Stat::Defense => 5,
});

let total = base.zip_with(bonus, |_stat, a, b| a + b);
assert_eq!(total.get(Stat::Hp), &120);
assert_eq!(total.get(Stat::Attack), &60);
assert_eq!(total.get(Stat::Defense), &35);
Source

pub fn map<U>(self, f: impl FnMut(K, V) -> U) -> EnumTable<K, U, N>

Consumes the table, returning a new one with each value transformed by f.

§Examples
use enum_table::{EnumTable, Enumerable};

#[derive(Enumerable, Copy, Clone)]
enum Size {
    Small,
    Medium,
    Large,
}

let table = EnumTable::<Size, i32, { Size::COUNT }>::from_fn(|size| match size {
    Size::Small => 1,
    Size::Medium => 2,
    Size::Large => 3,
});

let doubled = table.map(|_size, value| value * 2);

assert_eq!(doubled.get(Size::Small), &2);
assert_eq!(doubled.get(Size::Medium), &4);
assert_eq!(doubled.get(Size::Large), &6);
Source

pub fn for_each(&self, f: impl FnMut(K, &V))

Calls f with each variant and a reference to its value, in K::VARIANTS order.

§Examples
use enum_table::{EnumTable, Enumerable};

#[derive(Enumerable, Copy, Clone)]
enum Light {
    Red,
    Yellow,
    Green,
}

let table = EnumTable::<Light, i32, { Light::COUNT }>::from_fn(|light| match light {
    Light::Red => 1,
    Light::Yellow => 2,
    Light::Green => 3,
});

let mut sum = 0;
table.for_each(|_light, value| sum += value);
assert_eq!(sum, 6);
Source

pub fn for_each_mut(&mut self, f: impl FnMut(K, &mut V))

Transforms each value in the table in place via f.

§Examples
use enum_table::{EnumTable, Enumerable};

#[derive(Enumerable, Copy, Clone)]
enum Level {
    Low,
    Medium,
    High,
}

let mut table = EnumTable::<Level, i32, { Level::COUNT }>::from_fn(|level| match level {
    Level::Low => 10,
    Level::Medium => 20,
    Level::High => 30,
});

table.for_each_mut(|_level, value| *value += 5);

assert_eq!(table.get(Level::Low), &15);
assert_eq!(table.get(Level::Medium), &25);
assert_eq!(table.get(Level::High), &35);
Source§

impl<K: Enumerable, V: Copy, const N: usize> EnumTable<K, V, N>

Source

pub const fn from_elem(value: V) -> Self

Creates a new EnumTable with value copied into every slot.

§Examples
use enum_table::{EnumTable, Enumerable};

#[derive(Enumerable, Copy, Clone)]
enum Status {
    Active,
    Inactive,
    Pending,
}

let table = EnumTable::<Status, i32, { Status::COUNT }>::from_elem(42);

assert_eq!(table.get(Status::Active), &42);
assert_eq!(table.get(Status::Inactive), &42);
assert_eq!(table.get(Status::Pending), &42);
Source§

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

Source

pub fn clear(&mut self)

Resets every value in the table to V::default().

Source

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

Replaces the value associated with variant with V::default(), returning the previous value.

Trait Implementations§

Source§

impl<K: Enumerable, 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 (const: unstable) · Source§

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

Performs copy-assignment from source. Read more
Source§

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

Source§

impl<K: Enumerable + 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: Enumerable, 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: Enumerable, V: Eq, const N: usize> Eq for EnumTable<K, V, N>

Source§

impl<'a, K: Enumerable, V: Copy, const N: usize> Extend<(&'a K, &'a V)> for EnumTable<K, V, N>

Source§

fn extend<I: IntoIterator<Item = (&'a K, &'a V)>>(&mut self, iter: I)

Extends a collection with the contents of an iterator. Read more
Source§

fn extend_one(&mut self, item: T)

🔬This is a nightly-only experimental API. (extend_one)
Extends a collection with exactly one element.
Source§

fn extend_reserve(&mut self, additional: usize)

🔬This is a nightly-only experimental API. (extend_one)
Reserves capacity in a collection for the given number of additional elements. Read more
Source§

impl<K: Enumerable, V, const N: usize> Extend<(K, V)> for EnumTable<K, V, N>

Source§

fn extend<I: IntoIterator<Item = (K, V)>>(&mut self, iter: I)

Extends a collection with the contents of an iterator. Read more
Source§

fn extend_one(&mut self, item: T)

🔬This is a nightly-only experimental API. (extend_one)
Extends a collection with exactly one element.
Source§

fn extend_reserve(&mut self, additional: usize)

🔬This is a nightly-only experimental API. (extend_one)
Reserves capacity in a collection for the given number of additional elements. Read more
Source§

impl<K: Enumerable, 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: Enumerable, 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: Enumerable, 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: Enumerable, 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: Enumerable, 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: Enumerable, V, const N: usize> IntoIterator for EnumTable<K, V, N>

Source§

type Item = (K, V)

The type of the elements being iterated over.
Source§

type IntoIter = Map<Enumerate<IntoIter<V, N>>, fn((usize, V)) -> (K, V)>

Which kind of iterator are we turning this into?
Source§

fn into_iter(self) -> Self::IntoIter

Creates an iterator from a value. Read more
Source§

impl<'a, K: Enumerable, V, const N: usize> IntoIterator for &'a EnumTable<K, V, N>

Source§

type Item = (&'a K, &'a V)

The type of the elements being iterated over.
Source§

type IntoIter = Map<Enumerate<Iter<'a, V>>, fn((usize, &'a V)) -> (&'a K, &'a V)>

Which kind of iterator are we turning this into?
Source§

fn into_iter(self) -> Self::IntoIter

Creates an iterator from a value. Read more
Source§

impl<'a, K: Enumerable, V, const N: usize> IntoIterator for &'a mut EnumTable<K, V, N>

Source§

type Item = (&'a K, &'a mut V)

The type of the elements being iterated over.
Source§

type IntoIter = Map<Enumerate<IterMut<'a, V>>, fn((usize, &'a mut V)) -> (&'a K, &'a mut V)>

Which kind of iterator are we turning this into?
Source§

fn into_iter(self) -> Self::IntoIter

Creates an iterator from a value. Read more
Source§

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

Source§

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

Equality operator ==. Read more
1.0.0 (const: unstable) · Source§

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

Inequality operator !=. Read more

Auto Trait Implementations§

§

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

§

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

§

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

§

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

§

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

§

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

§

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

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 = !

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

fn try_from(value: U) -> Result<T, !>

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.