From 00000260b88792ddeed56e850c9febda4dad33cf Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Matej=20Jane=C5=BEi=C4=8D?= Date: Sat, 21 Dec 2024 12:47:20 +0100 Subject: [PATCH] fix: account for wrapping in grid.get and grid.get_mut --- src/grid_vec/grid.rs | 12 +++++++++++- src/grid_vec/point.rs | 2 +- 2 files changed, 12 insertions(+), 2 deletions(-) diff --git a/src/grid_vec/grid.rs b/src/grid_vec/grid.rs index 65e374b..f897054 100644 --- a/src/grid_vec/grid.rs +++ b/src/grid_vec/grid.rs @@ -43,7 +43,7 @@ impl Display for Grid { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { for (idx, cell) in self.grid.iter().enumerate() { write!(f, "{}", *cell as char)?; - if idx > 0 && idx % self.width == 0 { + if idx > 0 && (idx + 1) % self.width == 0 { writeln!(f)?; } } @@ -77,10 +77,20 @@ impl Grid { } pub fn get(&self, p: &Point) -> Option<&u8> { + if p.i >= self.grid.len() / self.width || p.j >= self.width { + return None; + } self.grid.get(p.i * self.width + p.j) } pub fn get_mut(&mut self, p: &Point) -> Option<&mut u8> { + if p.i >= self.grid.len() / self.width || p.j >= self.width { + return None; + } self.grid.get_mut(p.i * self.width + p.j) } + + pub fn size(&self) -> (usize, usize) { + (self.grid.len() / self.width, self.width) + } } diff --git a/src/grid_vec/point.rs b/src/grid_vec/point.rs index dcf2a55..d84905f 100644 --- a/src/grid_vec/point.rs +++ b/src/grid_vec/point.rs @@ -89,7 +89,7 @@ impl Point { #[macro_export] macro_rules! pnt { - ($i:literal, $j:literal) => { + ($i:expr, $j:expr) => { Point { i: $i, j: $j } }; }