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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
#[derive(Debug, Copy, Clone, PartialEq, Hash, Eq)]
pub struct GridIndex(usize, usize);
impl GridIndex {
pub fn new(column: usize, row: usize) -> Self {
Self(column, row)
}
pub fn column(&self) -> usize {
self.0
}
pub fn row(&self) -> usize {
self.1
}
pub(crate) fn to_linear_idx_in(&self, width: usize) -> usize {
if self.column() >= width {
panic!(
"can't convert {:?} to a linear index in a Grid of width {}",
self, width
);
}
self.row() * width + self.column()
}
}
impl From<(usize, usize)> for GridIndex {
fn from((column, row): (usize, usize)) -> Self {
GridIndex::new(column, row)
}
}
impl std::fmt::Display for GridIndex {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "({},{})", self.column(), self.row())
}
}
#[derive(Debug, Copy, Clone)]
pub(crate) enum LinearIndexError {
RowTooHigh,
ColumnTooHigh,
}
impl std::fmt::Display for LinearIndexError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let output = match self {
LinearIndexError::RowTooHigh => "row index is too high",
LinearIndexError::ColumnTooHigh => "column index is too high",
};
write!(f, "{}", output)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn to_linear_idx_in_test() {
let index = GridIndex::new(2, 3);
let linear = index.to_linear_idx_in(7);
assert_eq!(linear, 23);
}
}