Add From and FromGraph implementations for Graph and AppendGraph

This commit is contained in:
2026-09-28 23:58:30 +02:00
parent a9190f88db
commit 3478274959
3 changed files with 95 additions and 2 deletions
+35
View File
@@ -1,5 +1,8 @@
//! Concrete graph topology models.
use crate::maps::ElementMap;
use crate::traits::{GraphTopology, GraphTopologyAddition};
pub mod append_graph;
pub mod frozen_graph;
pub mod graph;
@@ -11,3 +14,35 @@ pub use frozen_graph::{
FrozenGraph, FrozenGraphEdgeMap, FrozenGraphIncidence, FrozenGraphVertexMap,
};
pub use graph::{Graph, GraphEdgeMap, GraphIncidence, GraphVertexMap};
/// Builds a new graph isomorphic to `source`.
///
/// The resulting graph type `G` must implement [`GraphTopologyAddition`] which is used to add
/// vertices and edges. `on_edge` is called for each edge in `source` together with the
/// corresponding new edge of the new graph, which callers can use to construct an edge mapping.
///
/// Used by the [`GraphTopologyAddition`] models' `From<&H>` and [`FromGraph`] implementations.
///
/// [`FromGraph`]: crate::traits::FromGraph
pub(crate) fn build_from_topology<G: GraphTopologyAddition, H: GraphTopology>(
source: &H,
vertex_default: G::Vertex,
mut on_edge: impl FnMut(H::Edge, G::Edge),
) -> (G, ElementMap<H::Vertex, G::Vertex>) {
let mut result = G::default();
result.reserve_vertices(source.vertex_count());
result.reserve_edges(source.edge_count());
let mut vertex_map = source.vertex_map(vertex_default);
for v in source.vertices() {
vertex_map[v] = result.add_vertex();
}
for e in source.edges() {
let (u, v) = source.incident_vertices(e);
let new_edge = result.add_edge(vertex_map[u], vertex_map[v]);
on_edge(e, new_edge);
}
(result, vertex_map)
}