kpreid / exhaust

Exhaustive iteration trait in Rust
https://docs.rs/exhaust/
Apache License 2.0
13 stars 2 forks source link

Indexable exhaustive types #20

Open kpreid opened 2 months ago

kpreid commented 2 months ago

Add a trait & derive for indexable types. Something like:

trait Indexable: Exhaust {
    /// Number of distinct values of this type.
    /// Equivalent to `Self::exhaust().len()`, but is a constant.
    const VALUE_COUNT: usize;

    /// Returns the position within `Self::exhaust()` that `value` may be found.
    /// Equivalent to `Self::exhaust().position(value).unwrap()`; note that a correct implementation cannot panic.
    fn to_index(value: &Self) -> usize;

    /// Equivalent to `Self::exhaust().nth(index).unwrap()`.
    /// Panics if `index >= Self::VALUE_COUNT`
    fn from_index(index: usize) -> self;
}

This allows building fixed-size, exhaustive mapping data structures like enum-map, but with the nestability that exhaust::Exhaust supports.

Exhaust iterators for this type should also override position() and nth() to be O(1), but we do not want this to be the sole interface because it may be undesirable to allocate the iterator first, and because they are tedious to use and have an unwrap().

kpreid commented 2 months ago

Further use cases: