From dd76355a70b72d23546c62ad51300bed44a71ece Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Stefan=20M=C3=BCller?= Date: Tue, 21 Oct 2025 16:36:53 +0200 Subject: [PATCH] Add iterator over neighbors of a vertex Graph::neighbors() --- src/models.rs | 25 +++++++++++++++++++++++-- 1 file changed, 23 insertions(+), 2 deletions(-) diff --git a/src/models.rs b/src/models.rs index ba8ad71..1163b97 100644 --- a/src/models.rs +++ b/src/models.rs @@ -13,10 +13,26 @@ pub struct VertexIncidenceHeader { pub first_incidence: Option, } +pub struct VertexNeighborIterator<'a> { + graph: &'a Graph, + incidence: Option, +} + +impl<'a> Iterator for VertexNeighborIterator<'a> { + type Item = Vertex; + + fn next(&mut self) -> Option { + let incidence = self.incidence?; + self.incidence = self.graph.next_incidences[incidence.0]; + Some(self.graph.incidence_vertices[incidence.0]) + } +} + // TODO: Graph cannot support deleting vertices because of the external indices "Vertex". They could be made stable with e.g. slotmap or generational arena. // TODO: Graph fields must not be public. // TODO: Add functions to reserve memory for vertices and edges. // TODO: Add function to delete edges. +// TODO: Add iterator of edges. pub struct Graph { // TODO: Index 'incidence_headers' by a 'Vertex' instead of 'Vertex.0'? pub incidence_headers: Vec, @@ -24,8 +40,6 @@ pub struct Graph { pub incidence_vertices: Vec, } -// TODO: Add iterator of edges. -// TODO: Add iterator of vertex neighbors, see 'fn add_adjacent()'. impl Graph { pub fn new() -> Graph { Graph { @@ -90,6 +104,13 @@ impl Graph { pub fn iter(&self) -> impl Iterator { (0..self.incidence_headers.len()).map(Vertex) } + + pub fn neighbors(&self, v: Vertex) -> impl Iterator { + VertexNeighborIterator { + graph: self, + incidence: self.incidence_headers[v.0].first_incidence, + } + } } #[cfg(test)]