4

I'm trying to wrap a vector to change its index behaviour, so that when an out of bounds access happens, instead of panicking it returns a reference to a dummy value, like so:

use std::ops::Index;

struct VecWrapper(Vec<()>);

impl Index<usize> for VecWrapper {
    type Output = ();
    fn index(&self, idx: usize) -> &() {
        if idx < self.0.len() {
            &self.0[idx]
        } else {
            &()
        }
    }
}

which works just fine for the implementation of Index, but trying to implement IndexMut the same way fails for obvious reasons. the type in my collection does not have a Drop implementation so no destructor needs to be called (other than freeing the memory).

the only solution I can think of is to have a static mutable array containing thousands of dummies, and distributing references to elements of this array, this is a horrible solution though it still leads to UB if there are ever more dummies borrowed than the size of the static array.

terepy
  • 79
  • 5

1 Answers1

6

Give the wrapper an additional field that's the dummy. It's got the same lifetime restrictions, and so can't be aliased.

Sebastian Redl
  • 69,373
  • 8
  • 123
  • 157