Returning an owning iterator to a Rc<Vec<T>>


#1

I’m writing some component that stores buffers and retrieves them on request. I’m storing some Rc<Vec> for some T, and I would like my get function to return an iterator to some vector that also participates in reference counting. Is there a better solution for this than writing a new Iterator that stores both the Rc and an index into the vector? That feels really cumbersome.


#2

A few ideas:

struct Buffer<T>(Rc<Vec<T>>);

impl<T> Buffer<T> {
    // Take a closure from outside, don't expose any iterator
    fn with_items<F: FnMut(&T)>(&self, f: F) {
        self.0.iter().for_each(f);
    }
    
    // boxed iterator that extends borrow of `self`
    fn iter<'a>(&'a self) -> Box<Iterator<Item=&'a T> + 'a> {
        Box::new(self.0.iter())
    }
    
    // unboxed iterator (nightly for now) that extends borrow of `self`
    fn iter_nightly<'a>(&'a self) -> impl Iterator<Item=&'a T> + 'a {
        self.0.iter()
    }
}