I would like to have a method that returns an Option of my custom Vec LargeIndexVec
. I've managed to implement indexing with a single value and with a Range, but I would like to return an Option instead of panicking when out of bounds.
I suspect that I might need to implement something with a SliceIndex<LargeIndex>
, so that I can provide either a single value, or a range as index. I've checked the get
implementation on Vec
and [T]
, but I don't know how to put the pieces together.
#![allow(dead_code, unused_variables)]
use std::ops::{Index, Range};
use std::slice::SliceIndex;
type LargeIndexType = u32;
#[derive(Copy, Clone, Debug)]
struct LargeIndex(LargeIndexType);
#[derive(Debug)]
struct LargeIndexVec(Vec<LargeIndex>);
impl Index<LargeIndex> for LargeIndexVec {
type Output = LargeIndex;
fn index(&self, index: LargeIndex) -> &Self::Output {
&self.0[index.0 as usize]
}
}
impl Index<Range<LargeIndex>> for LargeIndexVec {
type Output = [LargeIndex];
fn index(&self, index: Range<LargeIndex>) -> &Self::Output {
&self.0[index.start.0 as usize..index.end.0 as usize]
}
}
fn main() {
let i = LargeIndex(0);
let j = LargeIndex(2);
let v = LargeIndexVec(vec![LargeIndex(42), LargeIndex(43), LargeIndex(44)]);
dbg!(&v[i]);
dbg!(&v[i..j]);
// dbg!(&v.get(i)); // I would like to have this working
// dbg!(&v.get(i..j)); // I would like to have this working
}