Add GraphTopology::incidences(), update and add related tests

This commit is contained in:
2026-05-08 13:12:23 +02:00
parent d3fcd690a5
commit 0bcd270d12
4 changed files with 378 additions and 63 deletions
+31 -2
View File
@@ -7,6 +7,12 @@ pub struct Vertex(usize);
#[derive(Copy, Clone, PartialEq, Eq, Debug)]
pub struct Incidence(usize);
impl Incidence {
fn normalize(&self) -> Self {
Self(self.0 & !1)
}
}
struct VertexIncidenceHeader {
incidence_count: usize,
first_incidence: Option<Incidence>,
@@ -26,13 +32,29 @@ impl<'a> Iterator for AdjacentVertexIterator<'a> {
type Item = Vertex;
fn next(&mut self) -> Option<Self::Item> {
let incidence = self.incidence?;
let entry = &self.graph.incidences[incidence.0];
let current = self.incidence?;
let entry = &self.graph.incidences[current.0];
self.incidence = entry.next;
Some(entry.adjacent)
}
}
struct IncidenceIterator<'a> {
graph: &'a AppendGraph,
incidence: Option<Incidence>,
}
impl<'a> Iterator for IncidenceIterator<'a> {
type Item = (Vertex, Incidence);
fn next(&mut self) -> Option<Self::Item> {
let current = self.incidence?;
let entry = &self.graph.incidences[current.0];
self.incidence = entry.next;
Some((entry.adjacent, current.normalize()))
}
}
pub struct AppendGraph {
// TODO: Index 'vertices' by a 'Vertex' instead of 'Vertex.0'?
vertices: Vec<VertexIncidenceHeader>,
@@ -117,6 +139,13 @@ impl GraphTopology for AppendGraph {
(0..self.incidences.len()).step_by(2).map(Incidence)
}
fn incidences(&self, v: Self::Vertex) -> impl Iterator<Item = (Self::Vertex, Self::Edge)> {
IncidenceIterator {
graph: self,
incidence: self.vertices[v.0].first_incidence,
}
}
fn add_vertex(&mut self) -> Self::Vertex {
self.vertices.push(VertexIncidenceHeader {
incidence_count: 0,