pub trait SparseIndex: Sized {
// Required methods
fn index(&self) -> usize;
fn from_index(index: usize) -> Self;
}Expand description
A trait for types that can be infallibly converted to and from indices.
This trait is for types that have a bijective mapping with usize indices,
where every possible index value is valid. Examples include most enums
without gaps or wrapper types around indices.
For types that may have invalid index values, use TrySparseIndex
instead.
§Examples
use omp_core::sparse_index::TrySparseIndex;
#[repr(usize)]
#[derive(Copy, Clone, Debug)]
enum Color {
Red = 0,
Green = 1,
Blue = 2,
}
#[derive(Debug)]
struct ColorError(String);
impl std::fmt::Display for ColorError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.0)
}
}
impl std::error::Error for ColorError {}
impl TrySparseIndex for Color {
type Error = ColorError;
fn index(&self) -> usize {
*self as usize
}
fn try_from_index(index: usize) -> Result<Self, Self::Error> {
match index {
0 => Ok(Color::Red),
1 => Ok(Color::Green),
2 => Ok(Color::Blue),
_ => Err(ColorError("Invalid color index".to_string())),
}
}
}Required Methods§
Sourcefn from_index(index: usize) -> Self
fn from_index(index: usize) -> Self
Converts an index to this type.
§Panics
May panic if the index is not valid for this type. For fallible
conversion, implement TrySparseIndex instead.
Dyn Compatibility§
This trait is not dyn compatible.
In older versions of Rust, dyn compatibility was called "object safety".