Skip to content

Commit 537269d

Browse files
Improve grid helper
1 parent 7ca3784 commit 537269d

File tree

1 file changed

+21
-27
lines changed

1 file changed

+21
-27
lines changed

template/src/grid.rs

Lines changed: 21 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,9 @@ use std::{
66
ops::{Index, Range},
77
};
88

9-
pub const DIRS: [(i64, i64); 4] = [(1, 0), (-1, 0), (0, 1), (0, -1)];
9+
// Right, Down, Left, Up
10+
pub const DIRS: [(i64, i64); 4] = [(1, 0), (0, 1), (-1, 0), (0, -1)];
11+
1012
pub const CLOCKWISE: [(i64, i64); 8] = [
1113
(1, 0),
1214
(1, 1),
@@ -18,16 +20,26 @@ pub const CLOCKWISE: [(i64, i64); 8] = [
1820
(1, -1),
1921
];
2022

21-
pub trait ReadToGrid {
22-
fn read_to_grid(&self) -> Grid<char>;
23+
pub fn read_to_grid(filename: &str) -> Result<Grid<char>, std::io::Error> {
24+
Ok(fs::read_to_string(filename)?.to_grid())
2325
}
2426

25-
pub fn read_to_grid(filename: &str) -> Result<Grid<char>, std::io::Error> {
26-
let g = fs::read_to_string(filename)?
27-
.lines()
28-
.map(|l| l.chars().collect())
29-
.collect();
30-
Ok(Grid { grid: g })
27+
pub trait ToGrid {
28+
fn to_grid(&self) -> Grid<char>;
29+
}
30+
31+
impl ToGrid for &str {
32+
fn to_grid(&self) -> Grid<char> {
33+
Grid {
34+
grid: self.lines().map(|l| l.chars().collect()).collect(),
35+
}
36+
}
37+
}
38+
39+
impl ToGrid for String {
40+
fn to_grid(&self) -> Grid<char> {
41+
self.as_str().to_grid()
42+
}
3143
}
3244

3345
#[derive(Clone, PartialEq, Eq, Debug, Hash)]
@@ -66,16 +78,6 @@ impl<T: Copy> Grid<T> {
6678
self.grid[y as usize][x as usize] = c;
6779
}
6880

69-
#[inline]
70-
pub fn row_range(&self) -> Range<i64> {
71-
0..self.height()
72-
}
73-
74-
#[inline]
75-
pub fn col_range(&self) -> Range<i64> {
76-
0..self.width()
77-
}
78-
7981
pub fn iter(&self) -> GridIterator<T> {
8082
GridIterator {
8183
grid: self,
@@ -110,14 +112,6 @@ impl<'a, T: Copy> Iterator for GridIterator<'a, T> {
110112
}
111113
}
112114

113-
impl<T: Copy> Index<(i64, i64)> for Grid<T> {
114-
type Output = T;
115-
116-
fn index(&self, (x, y): (i64, i64)) -> &Self::Output {
117-
&self.grid[y as usize][x as usize]
118-
}
119-
}
120-
121115
impl<T: Copy + Display> Display for Grid<T> {
122116
fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), core::fmt::Error> {
123117
for row in self.grid.iter() {

0 commit comments

Comments
 (0)