distance_transform/
grid.rs1use std::slice::{Iter,IterMut};
5
6#[derive(Debug,Clone)]
8pub struct GenericGrid<T> {
9 data: Vec<T>,
10 width: usize,
11 height: usize,
12}
13
14impl<T: Default+Clone> GenericGrid<T> {
15 pub fn new(width: usize, height: usize) -> GenericGrid<T> {
18 GenericGrid { data: vec![T::default(); height*width], width, height }
19 }
20
21 pub fn height(&self) -> usize {
23 self.height
24 }
25
26 pub fn width(&self) -> usize {
28 self.width
29 }
30
31 pub fn get(&self, x: usize, y: usize) -> Option<&T> {
34 if x >= self.width || y >= self.height {
35 return None;
36 }
37 Some(self.get_unchecked(x, y))
38 }
39
40 pub fn get_unchecked(&self, x: usize, y: usize) -> &T {
43 &self.data[y*self.width+x]
44 }
45
46 pub fn set(&mut self, x: usize, y: usize, value: T) {
48 self.data[y*self.width+x] = value;
49 }
50
51 pub fn to_vec(self) -> Vec<T> {
54 self.data
55 }
56
57 pub fn iter(&self) -> GridIter<T> {
61 GridIter {
62 data_it: self.data.iter(),
63 width: self.width,
64 pos: 0,
65 }
66 }
67
68 pub fn iter_mut(&mut self) -> GridIterMut<T> {
72 GridIterMut {
73 data_it: self.data.iter_mut(),
74 width: self.width,
75 pos: 0,
76 }
77 }
78}
79
80#[derive(Debug)]
82pub struct GridIter<'a, T: 'a> {
83 data_it: Iter<'a, T>,
84 width: usize,
85 pos: usize,
86}
87
88impl<'a, T> Iterator for GridIter<'a, T> {
89 type Item = (usize, usize, &'a T);
90
91 fn next(&mut self) -> Option<Self::Item> {
92 match self.data_it.next() {
93 Some(val) => {
94 let res = (self.pos % self.width, self.pos/self.width, val);
95 self.pos += 1;
96 Some(res)
97 },
98 None => None,
99 }
100 }
101}
102
103#[derive(Debug)]
105pub struct GridIterMut<'a, T: 'a> {
106 data_it: IterMut<'a, T>,
107 width: usize,
108 pos: usize,
109}
110
111impl<'a, T> Iterator for GridIterMut<'a, T> {
112 type Item = (usize, usize, &'a mut T);
113
114 fn next(&mut self) -> Option<Self::Item> {
115 match self.data_it.next() {
116 Some(val) => {
117 let res = (self.pos % self.width, self.pos/self.width, val);
118 self.pos += 1;
119 Some(res)
120 },
121 None => None,
122 }
123 }
124}
125
126pub type FloatGrid = GenericGrid<f64>;
128
129pub type BoolGrid = GenericGrid<bool>;