From a16abd2697a74ec3697476eadc8b05ec59f1b080 Mon Sep 17 00:00:00 2001 From: tachsin Date: Wed, 23 Sep 2026 20:41:00 +0300 Subject: [PATCH] fix(grid): stop iterating a grid without columns The edge iterator, and the dense walks of GridIterator and GridIntoIterator, step x along a row and move to the next row when x comes back to width. With a width of zero x never does, so y never advances and the walk never ends. A grid without columns has no vertices, so all three now yield nothing. Fixes #842 --- src/grid.rs | 12 +++++++++--- tests/grid.rs | 21 +++++++++++++++++++++ 2 files changed, 30 insertions(+), 3 deletions(-) diff --git a/src/grid.rs b/src/grid.rs index 7ac0cd12..8abeb8d8 100644 --- a/src/grid.rs +++ b/src/grid.rs @@ -600,7 +600,9 @@ impl Iterator for GridIntoIterator { fn next(&mut self) -> Option { if self.grid.dense { loop { - if self.y == self.grid.height { + // With no columns, `x` would never come back to `width` and the walk would + // never move on to the next row. + if self.y == self.grid.height || self.grid.width == 0 { return None; } let r = (self.grid.has_vertex((self.x, self.y))).then_some((self.x, self.y)); @@ -646,7 +648,9 @@ impl Iterator for GridIterator<'_> { fn next(&mut self) -> Option { if self.grid.dense { loop { - if self.y == self.grid.height { + // With no columns, `x` would never come back to `width` and the walk would + // never move on to the next row. + if self.y == self.grid.height || self.grid.width == 0 { return None; } let r = (self.grid.has_vertex((self.x, self.y))).then_some((self.x, self.y)); @@ -698,7 +702,9 @@ impl Iterator for EdgesIterator<'_> { fn next(&mut self) -> Option { loop { - if self.y == self.grid.height { + // With no columns, `x` would never come back to `width` and the walk would never + // move on to the next row. + if self.y == self.grid.height || self.grid.width == 0 { return None; } let x = self.x; diff --git a/tests/grid.rs b/tests/grid.rs index 56ba3ebc..947498a7 100644 --- a/tests/grid.rs +++ b/tests/grid.rs @@ -666,3 +666,24 @@ fn iter_full_grid_yields_all_vertices() { via_into_iter.sort_unstable(); assert_eq!(via_into_iter, expected); } + +/// A grid without columns has no vertices. Walking it used to step `x` until it came back to +/// `width`, which with a width of zero never happens, so these loops never ended. +#[test] +fn a_grid_without_columns_iterates_to_nothing() { + let mut g = Grid::new(0, 5); + assert_eq!(g.edges().count(), 0); + g.fill(); + assert_eq!(g.iter().count(), 0); + assert_eq!(g.edges().count(), 0); + assert_eq!(g.into_iter().count(), 0); + + // The same state reached by shrinking a full grid. + let mut g = Grid::new(3, 3); + g.fill(); + assert!(g.resize(0, 3)); + assert_eq!(g.iter().count(), 0); + assert_eq!(g.edges().count(), 0); + assert_eq!(g.vertices_len(), 0); + assert_eq!(g.into_iter().count(), 0); +}