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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
pub struct Scanner {
    bytes: Vec<u8>,
    cols: usize,
    rows: usize,
}

impl Scanner {
    fn new(bytes: Vec<u8>, cols: usize, rows: usize) -> Self {
        Scanner { bytes, cols, rows }
    }

    fn index(&self, x: usize, y: usize) -> usize {
        x + self.rows * y
    }

    fn invert_index(&self, index: usize) -> (usize, usize) {
        (index % self.rows, index / self.rows)
    }

    pub fn get(&self, x: usize, y: usize) -> Option<u8> {
        self.bytes.get(self.index(x, y)).copied()
    }

    pub fn bytes<'a>(&'a self) -> impl Iterator<Item = u8> + 'a {
        self.bytes.iter().copied()
    }

    pub fn bytes_indices<'a>(&'a self) -> impl Iterator<Item = ((usize, usize), u8)> + 'a {
        self.bytes()
            .enumerate()
            .map(move |(i, b)| (self.invert_index(i), b))
    }
}

pub struct ScannerBuilder {
    bytes: Option<Vec<u8>>,
    cols: Option<usize>,
    rows: Option<usize>,
}

impl ScannerBuilder {
    pub fn with_cols(mut self, cols: usize) -> Self {
        self.cols = Some(cols);
        self
    }

    pub fn with_rows(mut self, rows: usize) -> Self {
        self.rows = Some(rows);
        self
    }
}