Rust - Index, mut Index operator example

less than 1 minute read

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
use std::ops::{Index, IndexMut};
#[derive(Debug)]
pub struct ImageArray2 {
    data: Vec<u8>,
    rows: usize,
    cols: usize,
}
impl ImageArray2 {
    pub fn new(rows: usize, cols: usize) -> ImageArray2 {
        let data = Vec::with_capacity(rows * cols);
        ImageArray2 {
            data: data,
            rows: rows,
            cols: cols,
        }
    }
}
impl Index<usize> for ImageArray2 {
    type Output = [u8];
    fn index(&self, index: usize) -> &Self::Output {
        &self.data[index * self.cols .. (index + 1) * self.cols]
    }
}
impl IndexMut<usize> for ImageArray2 {
    fn index_mut(&mut self, index: usize) -> &mut Self::Output {
        &mut self.data[index * self.cols .. (index + 1) * self.cols]
    }
}