Fix integer underflows in path and complete graph generators

This commit is contained in:
2026-10-22 20:37:32 +02:00
parent f5bb3ad07a
commit be7acfce1f
+10 -6
View File
@@ -60,10 +60,11 @@ where
/// ///
/// [Path graph]: https://en.wikipedia.org/wiki/Path_graph /// [Path graph]: https://en.wikipedia.org/wiki/Path_graph
pub fn path<G: GraphTopologyAddition>(graph: &mut G, n: usize) -> (Vec<G::Vertex>, Vec<G::Edge>) { pub fn path<G: GraphTopologyAddition>(graph: &mut G, n: usize) -> (Vec<G::Vertex>, Vec<G::Edge>) {
let edge_capacity = n.saturating_sub(1);
graph.reserve_vertices(n); graph.reserve_vertices(n);
graph.reserve_edges(n - 1); graph.reserve_edges(edge_capacity);
let vertices: Vec<_> = (0..n).map(|_| graph.add_vertex()).collect(); let vertices: Vec<_> = (0..n).map(|_| graph.add_vertex()).collect();
let edges = (0..n - 1) let edges = (0..edge_capacity)
.map(|i| graph.add_edge(vertices[i], vertices[i + 1])) .map(|i| graph.add_edge(vertices[i], vertices[i + 1]))
.collect(); .collect();
(vertices, edges) (vertices, edges)
@@ -97,12 +98,15 @@ pub fn cycle<G: GraphTopologyAddition>(graph: &mut G, n: usize) -> (Vec<G::Verte
/// For `n == 0`, nothing is added. For `n == 1`, only a single vertex is added. /// For `n == 0`, nothing is added. For `n == 1`, only a single vertex is added.
/// ///
/// [Complete graph]: https://en.wikipedia.org/wiki/Complete_graph /// [Complete graph]: https://en.wikipedia.org/wiki/Complete_graph
pub fn complete<G: GraphTopologyAddition>(graph: &mut G, n: usize) -> (Vec<G::Vertex>, Vec<G::Edge>) { pub fn complete<G: GraphTopologyAddition>(
let capacity = n * (n - 1) / 2; graph: &mut G,
n: usize,
) -> (Vec<G::Vertex>, Vec<G::Edge>) {
let edge_capacity = n * n.saturating_sub(1) / 2;
graph.reserve_vertices(n); graph.reserve_vertices(n);
graph.reserve_edges(capacity); graph.reserve_edges(edge_capacity);
let vertices: Vec<_> = (0..n).map(|_| graph.add_vertex()).collect(); let vertices: Vec<_> = (0..n).map(|_| graph.add_vertex()).collect();
let mut edges = Vec::with_capacity(capacity); let mut edges = Vec::with_capacity(edge_capacity);
for (i, &u) in vertices.iter().enumerate() { for (i, &u) in vertices.iter().enumerate() {
for &v in &vertices[i + 1..] { for &v in &vertices[i + 1..] {
edges.push(graph.add_edge(u, v)); edges.push(graph.add_edge(u, v));