Crate exhaustive_map

Crate exhaustive_map 

Source
Expand description

§exhaustive-map Latest Version API Docs

An exhaustive map for types with finite inhabitants.

Example usage:

use exhaustive_map::ExhaustiveMap;

let mut map = ExhaustiveMap::<u8, u16>::from_fn(|i| i as u16 + 100);
assert_eq!(map.len(), 256);

assert_eq!(map[3], 103);

map[7] = 9999;
assert_eq!(map[7], 9999);

map.swap(7, 3);
assert_eq!(map[3], 9999);
assert_eq!(map[7], 103);

The key type must implement the Finite trait. You can implement this for your own types using derive:

use exhaustive_map::{Finite, FiniteExt};

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

let all: Vec<_> = Color::iter_all().collect();
assert_eq!(all, vec![Color::Red, Color::Green, Color::Blue]);

The Finite trait can also be implemented manually:

use exhaustive_map::{Finite, typenum::consts::U3};

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

impl Finite for Color {
    type INHABITANTS = U3;

    fn to_usize(&self) -> usize {
        match self {
            Self::Red => 0,
            Self::Green => 1,
            Self::Blue => 2,
        }
    }

    fn from_usize(i: usize) -> Option<Self> {
        Some(match i {
            0 => Self::Red,
            1 => Self::Green,
            2 => Self::Blue,
            _ => return None,
        })
    }
}

§Features

  • serde - Enables serialization and deserialization of ExhaustiveMap. Example:
use exhaustive_map::{ExhaustiveMap, Finite};
use serde::Serialize;

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

let map = ExhaustiveMap::<Color, _>::from_usize_fn(|i| i);
let json = serde_json::to_string(&map).unwrap();
assert_eq!(json, r#"{"Red":0,"Green":1,"Blue":2}"#);

Re-exports§

pub use generic_array;
pub use generic_array::typenum;

Structs§

ExhaustiveMap
A map which is guaranteed to always contain a value for each possible key of type K.
InRange
A usize value that is guaranteed to be in the range A..B.
InRangeInclusive
A usize value that is guaranteed to be in the range A..=B.
IntoIter
An owning iterator over the entries of an ExhaustiveMap.
IntoValues
An owning iterator over the values of an ExhaustiveMap.
Iter
An iterator over the entries of an ExhaustiveMap.
IterAll
An owned iterator over all inhabitants of a type implementing Finite.
IterMut
A mutable iterator over the entries of an ExhaustiveMap.
Values
An iterator over the values of an ExhaustiveMap.
ValuesMut
A mutable iterator over the values of an ExhaustiveMap.

Traits§

Finite
Represents a type that has a finite number of inhabitants.
FiniteExt
An extension for Finite providing the iter_all method.
FitsInUsize
Implemented for typenum numbers which fits in an usize.
InRangeBounds

Derive Macros§

Finite