How to implement get for my custom vec of custom type

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
}

Playground link

the methods on SliceIndex are unstable, but something like this works. You can also make your own version of the SliceIndex trait and use that.

impl LargeIndexVec {
    fn get<I>(&self, idx: I) -> Option<&I::Output> where I: SliceIndex<[LargeIndex]> {
        idx.get(&self.0[..])
    }
}

Does this mean that I cannot implement a custom get method unless I use nightly?
I get an error[E0658]: use of unstable library feature 'slice_index_methods' when trying to compile this.

You can either use nightly or use your own trait that you implement for usize and RangeFull / RangeFrom etc.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.