I have a struct representing a vec-backed 2D image, inspired by the image crate:
pub struct Array2D<ElementType>
where ElementType: Primitive
{
data: Vec<ElementType>,
width: u32,
height: u32,
}
I want to iterate it mutably and immutably. Iterating by rows is simple:
impl<ElementType: Primitive> Array2D<ElementType> {
pub fn rows(&self) -> Chunks<ElementType> {
self.data.chunks(self.width as usize)
}
pub fn rows_mut(&mut self) -> ChunksMut<ElementType> {
self.data.chunks_mut(self.width as usize)
}
}
But trying to do the same thing over columns defeated me. I tried to write my own iterator:
pub struct ColumnIterMut<'a, ElemT>
{
current_col: usize,
stride: usize,
underlying: &'a mut Vec<ElemT>,
}
impl<'a, ElemT: Primitive> Iterator for ColumnIterMut<'a, ElemT> {
type Item = StepBy<IterMut<'a, ElemT>>;
fn next(&mut self) -> Option<Self::Item> {
if self.current_col >= self.stride {
None
} else {
let slice = &mut self.underlying[self.current_col as usize ..];
let ret = Some(
slice.iter_mut().step_by(self.stride as usize));
self.current_col += 1;
ret
}
}
}
This does not compile, apparently because the mutable reference inside the function can't outlive the function, although it's a reference to a &'a vector. If I remove the mutability everywhere, this iterator class compiles, even though the same lifetimes are involved.
I'm looking either for suggetions on how to mutably iterate over columns, or how to get my iterator attempt to succeed. Thanks in advance.