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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
pub struct Vec2d<T> {
data: Vec<T>,
width: usize,
}
impl<T: Default> Vec2d<T> {
pub fn new_with_default(rows: usize, cols: usize) -> Vec2d<T> {
Vec2d::new_empty(rows, cols).initialize_to_default()
}
pub fn add_row_of_default(&mut self) {
let size = self.count() + self.width;
while self.data.len() < size {
self.data.push(T::default());
}
}
fn initialize_to_default(mut self) -> Vec2d<T> {
let size = self.data.capacity();
while self.data.len() < size {
self.data.push(T::default());
}
self
}
}
impl<T: Copy> Vec2d<T> {
pub fn new_with_value(rows: usize, cols: usize, val:T) -> Vec2d<T> {
Vec2d::new_empty(rows, cols).initialize_to_value(val)
}
fn initialize_to_value(mut self, val: T) -> Vec2d<T> {
let size = self.data.capacity();
while self.data.len() < size {
self.data.push(val);
}
self
}
}
impl<T> Vec2d<T> {
pub fn new() -> Vec2d<T> {
Vec2d {
data: Vec::new(),
width: 0,
}
}
pub fn count(&self) -> usize {
self.width * self.count_rows()
}
pub fn count_cols(&self) -> usize {
self.width
}
pub fn count_rows(&self) -> usize {
if self.width == 0 { 0 } else { self.data.len() / self.width }
}
pub fn size(&self) -> (usize, usize) {
(self.count_rows(), self.count_cols())
}
fn new_empty(rows: usize, cols: usize) -> Vec2d<T> {
Vec2d {
data: Vec::with_capacity(rows*cols),
width: cols,
}
}
}
impl<T> std::ops::Index<usize> for Vec2d<T> {
type Output = [T];
fn index(&self, row: usize) -> &[T] {
let start = row * self.width;
let end = start + self.width;
&self.data[start..end]
}
}
impl<T> std::ops::IndexMut<usize> for Vec2d<T> {
fn index_mut<'a>(&'a mut self, row: usize) -> &'a mut Self::Output {
let start = row * self.width;
let end = start + self.width;
&mut self.data[start..end]
}
}