Trait hash_arr_map::IntoIndex [−][src]
pub trait IntoIndex {
fn into_index(&self) -> Option<Idx<Self>>;
}
Expand description
An attempted conversion into an Idx
.
This is used when converting a value into an appropriate index. Therefore,
only types that are integer-like should return Some
here.
Example:
use core::num::NonZeroUsize;
use hash_arr_map::{FromIndex, Idx, IntoIndex, NewIndex};
struct CouldBeAnIdx(i32);
impl IntoIndex for CouldBeAnIdx {
fn into_index(&self) -> Option<Idx<Self>> {
let nzu: NonZeroUsize = usize::try_from(self.0).ok()?.try_into().ok()?;
Some(unsafe { Idx::new(nzu) })
}
}
impl FromIndex for CouldBeAnIdx {
fn from_index(idx: Idx<Self>) -> Self {
Self(idx.get().get() as i32)
}
}
// Allow creating new indices out of thin air.
// To let `Ham::get_n` work.
unsafe impl NewIndex for CouldBeAnIdx {
fn new_index_allowed(idx: NonZeroUsize) -> bool {
i32::try_from(idx.get()).is_ok()
}
}
Required methods
fn into_index(&self) -> Option<Idx<Self>>
fn into_index(&self) -> Option<Idx<Self>>
Try to convert self
into an Idx
.
use core::num::NonZeroUsize;
use hash_arr_map::{Idx, IntoIndex};
let a: i32 = 5;
assert_eq!(
a.into_index(),
Some(unsafe { Idx::new(NonZeroUsize::new(5).unwrap()) })
);