-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgrid_mut.rs
More file actions
250 lines (222 loc) · 8.31 KB
/
grid_mut.rs
File metadata and controls
250 lines (222 loc) · 8.31 KB
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
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
use crate::cols_iter::ColsIter;
use crate::{Col, Coord, CoordComponent, Grid, GridIter, Row, RowsIter, View};
/// A type representing a mutable 2D array.
pub trait GridMut: Grid {
/// The root grid type. [Views](View) use this to store a reference to the root
/// grid so they can read and modify it.
type RootMut: GridMut<Item = Self::Item>;
/// The root grid for this one. If this grid is the root, this returns `self`.
fn root_mut(&mut self) -> &mut Self::RootMut;
/// Returns a mutable reference to the value stored at `(x, y)` in the grid,
/// or `None` if the provided coordinate is out of bounds.
fn get_mut(&mut self, x: usize, y: usize) -> Option<&mut Self::Item>;
/// Returns a mujtable reference to the value stored at `(x, y)` in the grid,
/// skipping any bounds checks.
///
/// For a safe alternative, see [`get_mut`](Self::get_mut).
///
/// # Safety
/// Calling this method with an out-of-bounds coord is *[undefined behavior]*
/// even if the resulting reference is not used.
///
/// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
unsafe fn get_unchecked_mut(&mut self, x: usize, y: usize) -> &mut Self::Item;
/// Returns a mutable reference to the value stored at the provided coordinate in
/// the grid, or `None` if the provided coordinate is out of bounds.
#[inline]
fn get_mut_at(&mut self, coord: impl Coord) -> Option<&mut Self::Item> {
self.get_mut(
coord.x().to_grid(self.width())?,
coord.y().to_grid(self.height())?,
)
}
/// Returns a mutable reference to the value stored at the provided coordinate
/// in the grid, skipping any bounds checks.
#[inline]
unsafe fn get_unchecked_mut_at(&mut self, coord: impl Coord) -> &mut Self::Item {
self.get_unchecked_mut(
coord.x().to_grid(self.width()).unwrap_unchecked(),
coord.y().to_grid(self.height()).unwrap_unchecked(),
)
}
/// Returns row `y` of the grid as a mutable slice if it is able to do so. Algorithms that
/// work on large portions of the grid may use this to look for performance gain. For
/// example, [`Row::draw_copied`] uses this internally to call std's [`copy_from_slice`] when
/// possible, which can be faster than manually copying elements one-by-one.
///
/// [`copy_from_slice`]: https://doc.rust-lang.org/std/primitive.slice.html#method.copy_from_slice
fn row_slice_mut(&mut self, y: usize) -> Option<&mut [Self::Item]>;
/// Returns row `y` of the grid as a mutable slice if it is able to do so. This variation
/// can take signed integers, or y-values in a [`Wrap`](crate::Wrap) or
/// [`Clamp`](crate::Clamp).
#[inline]
fn row_slice_mut_at(&mut self, y: impl CoordComponent) -> Option<&mut [Self::Item]> {
self.row_slice_mut(y.to_grid(self.height())?)
}
/// Replace the value stored at `(x, y)` in the grid. If the provided coordinate was
/// out of bounds, `None` is returned, otherwise the replaced value is returned.
#[inline]
fn set(&mut self, x: usize, y: usize, value: Self::Item) -> Option<Self::Item> {
self.get_mut(x, y)
.map(|curr| std::mem::replace(curr, value))
}
/// Replace the value stored at `(x, y)` in the grid, without bounds checking, and
/// return the replaced value.
///
/// For a safe alternative, see [`set`](Self::set).
///
/// # Safety
///
/// Calling this method with an out-of-bounds coord is *[undefined behavior]*.
///
/// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
#[inline]
unsafe fn set_unchecked(&mut self, x: usize, y: usize, value: Self::Item) -> Self::Item {
std::mem::replace(self.get_unchecked_mut(x, y), value)
}
/// Get a mutable [`View`] into this grid, or `None` if the provided region is
/// out of bounds.
#[inline]
fn try_view_mut(
&mut self,
x: usize,
y: usize,
w: usize,
h: usize,
) -> Option<View<&mut Self::RootMut>> {
if x.checked_add(w)? <= self.width() && y.checked_add(h)? <= self.height() {
let x = self.root_x() + x;
let y = self.root_y() + y;
Some(View::new(self.root_mut(), x, y, w, h))
} else {
None
}
}
/// Get a mutable [`View`] into this grid. Panicks if the provided region is out
/// of bounds.
#[inline]
fn view_mut(&mut self, x: usize, y: usize, w: usize, h: usize) -> View<&mut Self::RootMut> {
self.try_view_mut(x, y, w, h)
.expect("view does not overlap grid's bounds")
}
/// Mutably iterate over all values in the grid, with their positions.
#[inline]
fn iter_mut(&mut self) -> GridIter<&mut Self>
where
Self: Sized,
{
GridIter::new(self)
}
/// Mutably iterate over all columns in the grid.
#[inline]
fn cols_mut(&mut self) -> ColsIter<&mut Self>
where
Self: Sized,
{
ColsIter::new(self, self.width())
}
/// Return the column `x`, or `None` if `x` is out of bounds.
#[inline]
fn try_col_mut(&mut self, x: usize) -> Option<Col<&mut Self>> {
(x < self.width()).then(|| Col::new(self, x))
}
/// Return the column `x`. Panics if `x` is out of bounds.
#[inline]
fn col_mut(&mut self, x: usize) -> Col<&mut Self> {
self.try_col_mut(x).expect("column index out of bounds")
}
/// Mutably iterate over the rows of the grid.
#[inline]
fn rows_mut(&mut self) -> RowsIter<&mut Self>
where
Self: Sized,
{
RowsIter::new(self, self.height())
}
// Return the row `y`, or `None` if `y` is out of bounds.
#[inline]
fn try_row_mut(&mut self, y: usize) -> Option<Row<&mut Self>> {
(y < self.height()).then(|| Row::new(self, y))
}
/// Return the row `y`. Panics if `y` is out of bounds.
#[inline]
fn row_mut(&mut self, y: usize) -> Row<&mut Self> {
self.try_row_mut(y).expect("row index out of bounds")
}
/// Fill the entire grid with values provided by a function.
#[inline]
fn fill_with<F: FnMut() -> Self::Item>(&mut self, mut f: F)
where
Self: Sized,
{
for mut row in self.rows_mut() {
row.fill_with(&mut f);
}
}
/// Fill the entire grid with the provided value.
#[inline]
fn fill(&mut self, value: Self::Item)
where
Self: Sized,
Self::Item: Clone,
{
let mut rows = self.rows_mut();
if let Some(mut row) = rows.next() {
for mut row in rows {
row.fill(value.clone());
}
row.fill(value);
}
}
/// Clone all values from a source grid into this one. Panics if the grids
/// are not the same size.
#[inline]
fn draw_cloned<G2>(&mut self, grid: &G2)
where
G2: Grid<Item = Self::Item>,
G2::Item: Clone,
Self: Sized,
{
assert_eq!(self.width(), grid.width());
assert_eq!(self.height(), grid.height());
for (mut dst, src) in self.rows_mut().zip(grid.rows()) {
dst.draw_cloned(src);
}
}
/// Copy all values from a source grid into this one. Panics if the grids
/// are not the same size.
#[inline]
fn draw_copied<G2>(&mut self, grid: &G2)
where
G2: Grid<Item = Self::Item>,
G2::Item: Copy,
Self: Sized,
{
assert_eq!(self.width(), grid.width());
assert_eq!(self.height(), grid.height());
for (mut dst, src) in self.rows_mut().zip(grid.rows()) {
dst.draw_copied(src);
}
}
}
impl<T, const W: usize, const H: usize> GridMut for [[T; W]; H] {
type RootMut = Self;
#[inline]
fn root_mut(&mut self) -> &mut Self::RootMut {
self
}
#[inline]
fn get_mut(&mut self, x: usize, y: usize) -> Option<&mut Self::Item> {
(x < W && y < H).then(|| &mut self[y][x])
}
#[inline]
unsafe fn get_unchecked_mut(&mut self, x: usize, y: usize) -> &mut Self::Item {
self.as_mut_slice()
.get_unchecked_mut(y)
.get_unchecked_mut(x)
}
#[inline]
fn row_slice_mut(&mut self, y: usize) -> Option<&mut [Self::Item]> {
(y < H).then(|| self[y].as_mut_slice())
}
}