Index into Vec with a generic type

I have been working through the 2019 Advent of Code problems. There is a series of "Intcode" problems (Starting Here)

I've found this series of problems super helpful, as requirements for the 'Intcode' processor continue to evolve. One of the later requirements is the ability to support numbers up to i64::MAX. I'd like to make my struct generic. However, one part of the code demands that a 'memory address' is read from a positional argument at another memory address (IE: vec[3] = 4, so the value will be at vec[4])

Is it possible, using generics to create something that will be capable of indexing into itself using values stored in the 'memory vec'?

Here is some simple brainstorming code I came up with to work through the generic refactoring:

struct Register<T> {
    memory: Vec<T>,
}
impl<T> Register<T>
where
    T: Copy,
{
    fn read_positional(&self, position: usize) -> T {
        let pos_value = self.memory[position]; 

        // Problem HERE: How to get value from Vec and cast to usize, or index with it directly?
        //let value = self.memory[pos_value as usize];
        //let value = self.memory[pos_value.into()];
        
        value
    }
}

#[cfg(test)]
#[test]
fn read() {
    let a = 5u32;
    let b = a as usize;
    let reg32: Register<u32> = Register {
        memory: vec![1, 10],
    };
    assert_eq!(reg32.read_positional(0), 10);
}

Here's one way.

    fn read_positional(&self, position: usize) -> T
    where
        T: TryInto<usize>
    {
        let pos_value = self.memory[position]; 
        let idx = pos_value.try_into().unwrap_or_else(|_| {
            panic!("...be fallible or think up something reasonable to panic with here...")
        });

        self.memory[idx]
    }

(One way to panic would be to use usize::MAX I suppose.)

You'll never need indices larger than those that fit in usize, as that covers ~9.3 exabytes.

Of Course. But I'd like to be able to use the i64 stored in a position as a usize to index into a vec.

Thank you! This is helpful!

Making this generic has been a bear, as there are so many traits to add.

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.