From 8f9f0bf4c85f143c50bea6d4d91c52c6660efec8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Stefan=20M=C3=BCller?= Date: Fri, 17 Jul 2026 11:21:31 +0200 Subject: [PATCH 01/10] Add language tag to readme example code for syntax highlighting --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 9954e5b..417af7c 100644 --- a/README.md +++ b/README.md @@ -15,7 +15,7 @@ For more information, see the [documentation](https://docs.rs/grapherity/latest/ ## Example -``` +```rust // Brings commonly used traits into scope. use grapherity::prelude::*; use grapherity::models::Graph; From d9dc10299314769f3b2eb208cf7596a7ab4938ed Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Stefan=20M=C3=BCller?= Date: Fri, 24 Jul 2026 10:06:43 +0200 Subject: [PATCH 02/10] Add documentation for models::append_graph module --- src/models/append_graph.rs | 53 ++++++++++++++++++++++++++++++++++++-- 1 file changed, 51 insertions(+), 2 deletions(-) diff --git a/src/models/append_graph.rs b/src/models/append_graph.rs index 9ccfef7..89bbea6 100644 --- a/src/models/append_graph.rs +++ b/src/models/append_graph.rs @@ -1,13 +1,24 @@ use crate::maps::{EdgeMap, VertexMap}; use crate::traits::{GraphTopology, IncidenceCursor}; +/// An opaque handle identifying a vertex in an [`AppendGraph`]. +/// +/// Handles are stable for the lifetime of the graph. They can be obtained via graph methods like +/// [`GraphTopology::add_vertex`] and [`GraphTopology::vertices`]. #[derive(Copy, Clone, PartialEq, Eq, Debug)] pub struct Vertex(usize); +/// An opaque handle identifying an edge in an [`AppendGraph`]. +/// +/// Handles are stable for the lifetime of the graph. They can be obtained via graph methods like +/// [`GraphTopology::add_edge`] and [`GraphTopology::edges`]. #[derive(Copy, Clone, PartialEq, Eq, Debug)] pub struct Edge(usize); +/// A [`VertexMap`] for [`AppendGraph`] vertices. pub type AppendGraphVertexMap = VertexMap; + +/// An [`EdgeMap`] for [`AppendGraph`] edges. pub type AppendGraphEdgeMap = EdgeMap; impl Edge { @@ -16,6 +27,7 @@ impl Edge { } } +// TODO: Check if VertexIncidenceHeader and IncidenceEntry can be made smaller. Currently they both take 24 bytes (on 64bit), see https://stackoverflow.com/a/79653173 struct VertexIncidenceHeader { incidence_count: usize, first_incidence: Option, @@ -27,6 +39,10 @@ struct IncidenceEntry { adjacent: Vertex, } +/// A resumable cursor over the incidences of a single vertex in an [`AppendGraph`]. +/// +/// Can be obtained via [`GraphTopology::incidence_cursor`]. See [`IncidenceCursor`] on how to use +/// it. #[derive(Copy, Clone)] pub struct AppendGraphIncidenceCursor { incidence: Option, @@ -38,12 +54,45 @@ impl IncidenceCursor for AppendGraphIncidenceCursor { } } +/// An undirected graph that supports adding vertices and edges, but not deleting them. +/// +/// `AppendGraph` is optimised for workloads that incrementally build a graph and query it +/// repeatedly. [`Vertex`] +/// and [`Edge`] handles are never invalidated. Use [`Graph`] instead if you need to remove vertices +/// or edges. +/// +/// Incidences are stored as interlaced adjacency lists in a single flat [`Vec`]. This means that +/// vertex neighborhood traversals in general result in scattered index jumps. +/// +/// # Examples +/// +/// ``` +/// use grapherity::prelude::*; +/// use grapherity::models::AppendGraph; +/// +/// let mut graph = AppendGraph::new(); +/// let v1 = graph.add_vertex(); +/// let v2 = graph.add_vertex(); +/// let e = graph.add_edge(v1, v2); +/// assert!(graph.are_adjacent(v1, v2)); +/// ``` +/// +/// # Time and space complexity +/// +/// Both [`add_vertex`] and [`add_edge`] run in amortised *O(1)* time. [`degree`] runs in *O(1)* +/// time since vertex degrees are stored. Space complexity is *O(|V| + |E|)*. +/// +/// [`add_vertex`]: Self::add_vertex +/// [`add_edge`]: Self::add_edge +/// [`degree`]: Self::degree +/// [`Graph`]: crate::models::Graph pub struct AppendGraph { vertices: Vec, incidences: Vec, } impl AppendGraph { + /// Creates an empty graph instance with no vertices or edges. pub fn new() -> Self { Self { vertices: vec![], @@ -51,8 +100,8 @@ impl AppendGraph { } } - // Adds a single incidence of an edge, which is composed by two such incidences, to the - // incidences vector. + /// Adds a single incidence of an edge, which is composed by two such incidences, to the + /// incidences vector. fn add_incidence(&mut self, v1: Vertex, v2: Vertex) { self.incidences.push(IncidenceEntry { next: self.vertices[v1.0].first_incidence.take(), From 21e79c660f42457bdbb4ee89003623a1dd85434e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Stefan=20M=C3=BCller?= Date: Fri, 24 Jul 2026 20:55:01 +0200 Subject: [PATCH 03/10] Update documentation for AppendGraph --- src/models/append_graph.rs | 24 ++++++++++++------------ 1 file changed, 12 insertions(+), 12 deletions(-) diff --git a/src/models/append_graph.rs b/src/models/append_graph.rs index 89bbea6..715e0c3 100644 --- a/src/models/append_graph.rs +++ b/src/models/append_graph.rs @@ -1,17 +1,19 @@ +//! [`AppendGraph`], an undirected graph topology supporting addition only. + use crate::maps::{EdgeMap, VertexMap}; use crate::traits::{GraphTopology, IncidenceCursor}; /// An opaque handle identifying a vertex in an [`AppendGraph`]. /// -/// Handles are stable for the lifetime of the graph. They can be obtained via graph methods like -/// [`GraphTopology::add_vertex`] and [`GraphTopology::vertices`]. +/// Handles are stable for the lifetime of the graph. Obtain via graph methods like +/// [`AppendGraph::add_vertex`] and [`AppendGraph::vertices`]. #[derive(Copy, Clone, PartialEq, Eq, Debug)] pub struct Vertex(usize); /// An opaque handle identifying an edge in an [`AppendGraph`]. /// -/// Handles are stable for the lifetime of the graph. They can be obtained via graph methods like -/// [`GraphTopology::add_edge`] and [`GraphTopology::edges`]. +/// Handles are stable for the lifetime of the graph. Obtain via graph methods like +/// [`AppendGraph::add_edge`] and [`AppendGraph::edges`]. #[derive(Copy, Clone, PartialEq, Eq, Debug)] pub struct Edge(usize); @@ -41,8 +43,7 @@ struct IncidenceEntry { /// A resumable cursor over the incidences of a single vertex in an [`AppendGraph`]. /// -/// Can be obtained via [`GraphTopology::incidence_cursor`]. See [`IncidenceCursor`] on how to use -/// it. +/// Obtain via [`AppendGraph::incidence_cursor`]. See [`IncidenceCursor`] on usage guidance. #[derive(Copy, Clone)] pub struct AppendGraphIncidenceCursor { incidence: Option, @@ -57,12 +58,11 @@ impl IncidenceCursor for AppendGraphIncidenceCursor { /// An undirected graph that supports adding vertices and edges, but not deleting them. /// /// `AppendGraph` is optimised for workloads that incrementally build a graph and query it -/// repeatedly. [`Vertex`] -/// and [`Edge`] handles are never invalidated. Use [`Graph`] instead if you need to remove vertices -/// or edges. +/// repeatedly. [`Vertex`] and [`Edge`] handles are never invalidated. Use [`Graph`] instead if you +/// need to remove vertices or edges. /// -/// Incidences are stored as interlaced adjacency lists in a single flat [`Vec`]. This means that -/// vertex neighborhood traversals in general result in scattered index jumps. +/// Incidences are stored as interleaved adjacency lists in a single flat [`Vec`]. In general, +/// vertex neighborhood traversals result in scattered index jumps. /// /// # Examples /// @@ -77,7 +77,7 @@ impl IncidenceCursor for AppendGraphIncidenceCursor { /// assert!(graph.are_adjacent(v1, v2)); /// ``` /// -/// # Time and space complexity +/// # Time and space complexity /// /// Both [`add_vertex`] and [`add_edge`] run in amortised *O(1)* time. [`degree`] runs in *O(1)* /// time since vertex degrees are stored. Space complexity is *O(|V| + |E|)*. From b5cc3b1c3f81f68bbd2584e3045d24ee63527a50 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Stefan=20M=C3=BCller?= Date: Fri, 24 Jul 2026 20:55:41 +0200 Subject: [PATCH 04/10] Add documentation for Graph --- src/models/graph.rs | 83 +++++++++++++++++++++++++++++++++++++++++---- 1 file changed, 76 insertions(+), 7 deletions(-) diff --git a/src/models/graph.rs b/src/models/graph.rs index ed86205..c4da097 100644 --- a/src/models/graph.rs +++ b/src/models/graph.rs @@ -1,12 +1,26 @@ +//! [`Graph`], an undirected graph topology supporting addition and deletion. + use typed_generational_arena::{Arena, Index}; use crate::maps::{EdgeMap, VertexMap}; use crate::traits::{GraphTopology, GraphTopologyDeletion, IncidenceCursor}; +/// An opaque handle identifying a vertex in a [`Graph`]. +/// +/// Handles remain valid until the vertex is explicitly deleted. Obtain via graph methods like +/// [`Graph::add_vertex`] and [`Graph::vertices`]. pub type Vertex = Index; + +/// An opaque handle identifying an edge in a [`Graph`]. +/// +/// Handles remain valid until the edge is explicitly deleted, or one of its endpoint vertices is +/// deleted. Obtain via graph methods like [`Graph::add_edge`] and [`Graph::edges`]. pub type Edge = Index; +/// A [`VertexMap`] for [`Graph`] vertices. pub type GraphVertexMap = VertexMap; + +/// An [`EdgeMap`] for [`Graph`] edges. pub type GraphEdgeMap = EdgeMap; #[derive(Copy, Clone, PartialEq, Eq, Debug)] @@ -15,11 +29,18 @@ struct VertexSlot(usize); #[derive(Copy, Clone, PartialEq, Eq, Debug)] struct IncidenceSlot(usize); +// TODO: Check if VertexIncidenceHeader and IncidenceEntry can be made smaller. Currently they both take 24 bytes (on 64bit), see https://stackoverflow.com/a/79653173 +/// `pub` because [`Vertex`] references it as a type parameter of the underlying arena. Not +/// intended for direct external use. +#[doc(hidden)] pub struct VertexIncidenceHeader { incidence_count: usize, first_incidence: Option, } +/// `pub` because [`Edge`] references it as a type parameter of the underlying arena. Not intended +/// for direct external use. +#[doc(hidden)] #[derive(Copy, Clone)] pub struct IncidenceEntry { next: Option, @@ -36,6 +57,9 @@ impl IncidentEdgeCursor { } } +/// A resumable cursor over the incidences of a single vertex in a [`Graph`]. +/// +/// Obtain via [`Graph::incidence_cursor`]. See [`IncidenceCursor`] on usage guidance. #[derive(Copy, Clone)] pub struct GraphIncidenceCursor { incidence: Option, @@ -49,6 +73,49 @@ impl IncidenceCursor for GraphIncidenceCursor { } } +/// An undirected graph that supports adding vertices and edges, and deleting them. +/// +/// `Graph` is suited for workloads that need to modify the graph structure over time, i.e. adding +/// amd removing vertices and edges. [`Vertex`] and [`Edge`] handles remain valid until the vertex +/// or edge they identify is explicitly deleted. Use [`AppendGraph`] instead if you only need to +/// append vertices and edges. +/// +/// Incidences are stored as interleaved adjacency lists in a generational [`Arena`]. In general, +/// vertex neighborhood traversals result in scattered memory accesses. +/// +/// # Examples +/// +/// ``` +/// use grapherity::prelude::*; +/// use grapherity::models::Graph; +/// +/// let mut graph = Graph::new(); +/// let v1 = graph.add_vertex(); +/// let v2 = graph.add_vertex(); +/// let _e = graph.add_edge(v1, v2); +/// assert!(graph.are_adjacent(v1, v2)); +/// graph.delete_vertex(v1); +/// assert_eq!(graph.degree(v2), 0); +/// ``` +/// +/// # Time and space complexity +/// +/// Both [`add_vertex`] and [`add_edge`] run in amortised *O(1)* time. [`degree`] runs in *O(1)* +/// time since vertex degrees are stored. [`delete_vertex`] runs in *O(degree(v))* time. +/// [`delete_edge`] runs in *O(degree(u) + degree(v))* time, where *u* and *v* are the edge's +/// endpoints. +/// +/// Space complexity is *O(|V| + |E|)*, but freed slots for vertices and edges are not compacted and +/// their allocation is never reclaimed. Capacity only grows. If additions and deletions are both +/// planned, performing deletions first allows freed slots to be reused by subsequent additions, +/// potentially avoiding reallocation. +/// +/// [`add_vertex`]: Self::add_vertex +/// [`add_edge`]: Self::add_edge +/// [`degree`]: Self::degree +/// [`delete_vertex`]: Self::delete_vertex +/// [`delete_edge`]: Self::delete_edge +/// [`AppendGraph`]: crate::models::AppendGraph pub struct Graph { // TODO: Arena index and generation types could be externalized to Graph. vertices: Arena, @@ -56,6 +123,7 @@ pub struct Graph { } impl Graph { + /// Creates an empty graph instance with no vertices or edges. pub fn new() -> Self { Self { vertices: Arena::new(), @@ -63,8 +131,8 @@ impl Graph { } } - // Adds a single incidence of an edge, which is composed by two such incidences, to the - // incidences arena, and returns its index. + /// Adds a single incidence of an edge, which is composed by two such incidences, to the + /// incidences arena, and returns its index. fn add_incidence(&mut self, v1: Vertex, v2: Vertex) -> Edge { let edge = self.incidences.insert(IncidenceEntry { next: self.vertices[v1].first_incidence.take(), @@ -91,8 +159,9 @@ impl Graph { (f, e_entry, f_entry) } - // Updates the source vertex incidence list after the incidence "e" was deleted from the - // incidence arena. "next" is the next incidence after "e" in the source vertex incidence list. + /// Updates the `source` vertex incidence list after the incidence `e` was deleted from the + /// incidence arena. `next` is the next incidence after `e` in the `source` vertex incidence + /// list. fn update_incidence_list( &mut self, e: Edge, @@ -267,10 +336,10 @@ impl GraphTopologyDeletion for Graph { } } - // The incidence entries are removed before patching the linked lists. This is safe because - // update_incidence_list() searches by raw slot index (IncidenceSlot.0) and only dereferences - // the predecessor, never the removed entries themselves. fn delete_edge(&mut self, e: Self::Edge) { + // The incidence entries are removed before patching the linked lists. This is safe because + // `update_incidence_list` searches by raw slot index (IncidenceSlot.0) and only + // dereferences the predecessor, never the removed entries themselves. let (f, e_entry, f_entry) = self.remove_incidence_pair(e); if e_entry.adjacent != f_entry.adjacent { self.update_incidence_list(e, f_entry.adjacent, e_entry.next, false); From 6e80b2fc9a78ed0b362b83f131f42e1dfd494192 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Stefan=20M=C3=BCller?= Date: Fri, 24 Jul 2026 20:56:39 +0200 Subject: [PATCH 05/10] Update traits module documentation --- src/traits.rs | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/src/traits.rs b/src/traits.rs index 7c948c2..e03b52b 100644 --- a/src/traits.rs +++ b/src/traits.rs @@ -1,14 +1,17 @@ +//! Core traits for undirected graph topologies. + use crate::maps::{EdgeMap, VertexMap}; // TODO: Add functions to reserve memory for vertices and edges. // TODO: Split out GraphTopologyAddition trait. +// TODO: Introduce an Incidence struct. /// A trait representing an undirected graph topology. /// /// An undirected graph is a set of vertices and undirected edges, where each edge connects either /// exactly two vertices or one vertex with itself (loop edge). This trait provides methods for /// querying a graph topology, iterating over vertices and edges, and adding new vertices and edges. /// -/// # Vertices and Edges +/// # Vertices and edges /// /// Vertices and edges are identified by opaque handles ([`Vertex`] and [`Edge`]) that implement /// [`Copy`] and [`Eq`]. Handles remain valid for the lifetime of the graph unless the graph also From 99bab32f8c8759579bbe0db2bcd49e08c515b57b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Stefan=20M=C3=BCller?= Date: Fri, 24 Jul 2026 20:57:19 +0200 Subject: [PATCH 06/10] Add module level documentation for prelude, models, and testing --- src/lib.rs | 1 + src/models.rs | 2 ++ src/testing.rs | 2 ++ 3 files changed, 5 insertions(+) diff --git a/src/lib.rs b/src/lib.rs index 892c8aa..a926085 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -134,6 +134,7 @@ pub mod maps; pub mod models; pub mod traits; +/// Convenience re-exports of graph topology traits for common use. pub mod prelude { pub use crate::traits::{GraphTopology, GraphTopologyDeletion}; } diff --git a/src/models.rs b/src/models.rs index d6b95a4..4eb163e 100644 --- a/src/models.rs +++ b/src/models.rs @@ -1,3 +1,5 @@ +//! Concrete graph topology models. + pub mod append_graph; pub mod graph; diff --git a/src/testing.rs b/src/testing.rs index a345512..3412447 100644 --- a/src/testing.rs +++ b/src/testing.rs @@ -1,3 +1,5 @@ +//! Test fixture and test macros for graph topology and algorithm implementations. + pub(crate) mod bfs_testing; pub(crate) mod dfs_testing; pub(crate) mod dijkstra_testing; From 43c4ba45a22b3ec7927e0fdff7736186444070c5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Stefan=20M=C3=BCller?= Date: Mon, 27 Jul 2026 08:47:19 +0200 Subject: [PATCH 07/10] Add documentation for maps module --- src/maps.rs | 39 +++++++++++++++++++++++++++++++++++++-- 1 file changed, 37 insertions(+), 2 deletions(-) diff --git a/src/maps.rs b/src/maps.rs index 277ceb5..882e7ba 100644 --- a/src/maps.rs +++ b/src/maps.rs @@ -1,19 +1,39 @@ +//! Provides maps to associate custom data to graph vertices and edges. +//! +//! [`VertexMap`] and [`EdgeMap`] provide copy-on-write, [`Vec`]-backed maps to associate data to +//! all vertices or all edges in a graph, respectively. + use std::ops::{Index, IndexMut}; use crate::traits::GraphTopology; +/// A map to associate custom data to graph vertices. +/// +/// This map uses raw entity indices to associate homogenous custom data of type `T` to graph +/// vertices. The implementation uses a [`Vec`], allocating contiguous slots for the data, which +/// means that the provided index conversion function should map vertices to contiguous indices, or +/// indices with relatively few gaps. +/// +/// Data allocation happens as copy-on-write, i.e. the backing [`Vec`] is only resized if a value +/// beyond current capacity is written, but the `default` value can transparently be read. No bound +/// or validity checks are performed by the map on the provided vertex handles. +/// +/// Use [`GraphTopology::vertex_map`] to obtain a `VertexMap`. pub struct VertexMap { inner: EntityMap, } impl VertexMap { + /// Creates a new map with the given `default` value, an index conversion function `to_index`, + /// and an initial `capacity`. pub fn new(default: T, to_index: fn(V) -> usize, capacity: usize) -> Self { Self { inner: EntityMap::new(default, to_index, capacity), } } - // Reads beyond 'capacity' are valid and return the default value. + /// Returns the total number of data entries the map can write without reallocating. Reads + /// beyond `capacity` are valid and return the default value. pub fn capacity(&self) -> usize { self.inner.capacity() } @@ -42,18 +62,33 @@ impl IndexMut for VertexMap { } } +/// A map to associate custom data to graph edges. +/// +/// This map uses raw entity indices to associate homogenous custom data of type `T` to graph edges. +/// The implementation uses a [`Vec`], allocating contiguous slots for the data, which means that +/// the provided index conversion function should map edges to contiguous indices, or indices with +/// relatively few gaps. +/// +/// Data allocation happens as copy-on-write, i.e. the backing [`Vec`] is only resized if a value +/// beyond current capacity is written, but the `default` value can transparently be read. No bound +/// or validity checks are performed by the map on the provided edge handles. +/// +/// Use [`GraphTopology::edge_map`] to obtain an `EdgeMap`. pub struct EdgeMap { inner: EntityMap, } impl EdgeMap { + /// Creates a new map with the given `default` value, an index conversion function `to_index`, + /// and an initial `capacity`. pub fn new(default: T, to_index: fn(E) -> usize, capacity: usize) -> Self { Self { inner: EntityMap::new(default, to_index, capacity), } } - // Reads beyond 'capacity' are valid and return the default value. + /// Returns the total number of data entries the map can write without reallocating. Reads + /// beyond `capacity` are valid and return the default value. pub fn capacity(&self) -> usize { self.inner.capacity() } From 08b2c4db65122e825cf366c1edf789ab503df5b8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Stefan=20M=C3=BCller?= Date: Mon, 27 Jul 2026 09:58:41 +0200 Subject: [PATCH 08/10] Add documentation for Dijkstra's algorithm, and rearrange related functions --- src/algorithms.rs | 135 +++++++++++++++++++++++++++++++++++++++++++--- 1 file changed, 128 insertions(+), 7 deletions(-) diff --git a/src/algorithms.rs b/src/algorithms.rs index b974441..3f2aa0e 100644 --- a/src/algorithms.rs +++ b/src/algorithms.rs @@ -1,3 +1,33 @@ +//! Algorithms for graph topologies. +//! +//! # Dijkstra's algorithm +//! +//! [Dijkstra's algorithm] finds the shortest distances from a source vertex to all other vertices +//! in the graph. Note that for unweighted graphs it has worse time and space complexity than +//! [Breadth-first search](#breadth-first-search). +//! +//! Variants: [`dijkstra`], [`dijkstra_distances`], [`dijkstra_unweighted`], +//! [`dijkstra_distances_unweighted`]. +//! +//! # Breadth-first search +//! +//! [Breadth-first search] traverses a graph topology, exploring all neighboring vertices first +//! before descending further into their neighborhoods. +//! +//! Variants: [`bfs`], [`bfs_distances`], [`bfs_find`], [`bfs_find_where`] +//! +//! # Depth-first search +//! +//! [Depth-first search] traverses a graph topology, exploring each branch path as far as possible +//! first before backtracking and exploring other branches. +//! +//! Variants: [`dfs`], [`dfs_visited`], [`dfs_find`], [`dfs_find_where`], [`dfs_find_path`], +//! [`dfs_find_path_where`] +//! +//! [Breadth-first search]: https://en.wikipedia.org/wiki/Breadth-first_search +//! [Depth-first search]: https://en.wikipedia.org/wiki/Depth-first_search +//! [Dijkstra's algorithm]: https://en.wikipedia.org/wiki/Dijkstra%27s_algorithm + use std::cmp::Ordering; use std::collections::{BinaryHeap, VecDeque}; @@ -22,12 +52,39 @@ impl Ord for DistanceOrderedVertex { } } +/// Return data type for [`dijkstra`] and [`dijkstra unweighted`]. pub struct DijkstraResult { + /// Vertex map of minimum distances from a given `source` vertex. pub distances: VertexMap>, + + /// Vertex map of predecessors on some shortest path from a given `source` vertex. pub predecessors: VertexMap>, } // TODO: Generalize the return type of the weight function. +/// Dijkstra's algorithm with custom edge weights, returns minimum distances and predecessors. +/// +/// # Panics +/// +/// Panics if `source` is not a valid vertex of `graph`. +/// +/// # Examples +/// +/// ``` +/// # use grapherity::prelude::*; +/// # use grapherity::algorithms::dijkstra; +/// # use grapherity::models::Graph; +/// let mut graph = Graph::new(); +/// let source = graph.add_vertex(); +/// let target = graph.add_vertex(); +/// let e = graph.add_edge(source, target); +/// let mut weights = graph.edge_map(1); +/// weights[e] = 5; +/// +/// let result = dijkstra(&graph, source, |e| weights[e]); +/// assert_eq!(result.distances[target], Some(5)); +/// assert_eq!(result.predecessors[target], Some(source)); +/// ``` pub fn dijkstra(graph: &G, source: G::Vertex, weight: W) -> DijkstraResult where G: GraphTopology, @@ -43,13 +100,28 @@ where } } -pub fn dijkstra_unweighted(graph: &G, source: G::Vertex) -> DijkstraResult -where - G: GraphTopology, -{ - dijkstra(graph, source, |_| 1) -} - +/// Dijkstra's algorithm with custom edge weights, returns minimum distances. +/// +/// # Panics +/// +/// Panics if `source` is not a valid vertex of `graph`. +/// +/// # Examples +/// +/// ``` +/// # use grapherity::prelude::*; +/// # use grapherity::algorithms::{dijkstra, dijkstra_distances}; +/// # use grapherity::models::Graph; +/// let mut graph = Graph::new(); +/// let source = graph.add_vertex(); +/// let target = graph.add_vertex(); +/// let e = graph.add_edge(source, target); +/// let mut weights = graph.edge_map(1); +/// weights[e] = 5; +/// +/// let distances = dijkstra_distances(&graph, source, |e| weights[e]); +/// assert_eq!(distances[target], Some(5)); +/// ``` pub fn dijkstra_distances( graph: &G, source: G::Vertex, @@ -62,6 +134,55 @@ where dijkstra_impl(graph, source, weight, |_, _| {}) } +/// Dijkstra's algorithm with constant weights of *1* for all edges, returns minimum distances and +/// predecessors. +/// +/// # Panics +/// +/// Panics if `source` is not a valid vertex of `graph`. +/// +/// # Examples +/// +/// ``` +/// # use grapherity::prelude::*; +/// # use grapherity::algorithms::{dijkstra, dijkstra_unweighted}; +/// # use grapherity::models::Graph; +/// let mut graph = Graph::new(); +/// let source = graph.add_vertex(); +/// let target = graph.add_vertex(); +/// graph.add_edge(source, target); +/// +/// let result = dijkstra_unweighted(&graph, source); +/// assert_eq!(result.distances[target], Some(1)); +/// assert_eq!(result.predecessors[target], Some(source)); +/// ``` +pub fn dijkstra_unweighted(graph: &G, source: G::Vertex) -> DijkstraResult +where + G: GraphTopology, +{ + dijkstra(graph, source, |_| 1) +} + +/// Dijkstra's algorithm with constant weights of *1* for all edges, returns minimum distances. +/// +/// # Panics +/// +/// Panics if `source` is not a valid vertex of `graph`. +/// +/// # Examples +/// +/// ``` +/// # use grapherity::prelude::*; +/// # use grapherity::algorithms::{dijkstra, dijkstra_distances_unweighted}; +/// # use grapherity::models::Graph; +/// let mut graph = Graph::new(); +/// let source = graph.add_vertex(); +/// let target = graph.add_vertex(); +/// graph.add_edge(source, target); +/// +/// let distances = dijkstra_distances_unweighted(&graph, source); +/// assert_eq!(distances[target], Some(1)); +/// ``` pub fn dijkstra_distances_unweighted( graph: &G, source: G::Vertex, From 9a1e2faa9a16ba61476c2257410ad641cf663d8e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Stefan=20M=C3=BCller?= Date: Tue, 28 Jul 2026 22:56:51 +0200 Subject: [PATCH 09/10] Allow missing docs on deprecated maps methods --- src/maps.rs | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/maps.rs b/src/maps.rs index 882e7ba..3756444 100644 --- a/src/maps.rs +++ b/src/maps.rs @@ -39,10 +39,12 @@ impl VertexMap { } #[deprecated(since = "0.2.2", note = "use 'capacity' instead")] + #[allow(missing_docs)] pub fn len(&self) -> usize { self.capacity() } + #[allow(missing_docs)] pub fn sync>(&mut self, graph: &G) { self.inner.resize(graph.vertex_capacity()); } @@ -94,10 +96,12 @@ impl EdgeMap { } #[deprecated(since = "0.2.2", note = "use 'capacity' instead")] + #[allow(missing_docs)] pub fn len(&self) -> usize { self.capacity() } + #[allow(missing_docs)] pub fn sync>(&mut self, graph: &G) { self.inner.resize(graph.edge_capacity()); } From cf1dafceb786a6a6adddcacd1236b10ba16901fc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Stefan=20M=C3=BCller?= Date: Tue, 28 Jul 2026 22:57:55 +0200 Subject: [PATCH 10/10] Add remaining docs for algorithms module --- src/algorithms.rs | 344 ++++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 331 insertions(+), 13 deletions(-) diff --git a/src/algorithms.rs b/src/algorithms.rs index 3f2aa0e..5c6d147 100644 --- a/src/algorithms.rs +++ b/src/algorithms.rs @@ -14,15 +14,15 @@ //! [Breadth-first search] traverses a graph topology, exploring all neighboring vertices first //! before descending further into their neighborhoods. //! -//! Variants: [`bfs`], [`bfs_distances`], [`bfs_find`], [`bfs_find_where`] +//! Variants: [`bfs`], [`bfs_distances`], [`bfs_find`], [`bfs_find_where`]. //! -//! # Depth-first search +//! # Depth-first search //! //! [Depth-first search] traverses a graph topology, exploring each branch path as far as possible //! first before backtracking and exploring other branches. //! //! Variants: [`dfs`], [`dfs_visited`], [`dfs_find`], [`dfs_find_where`], [`dfs_find_path`], -//! [`dfs_find_path_where`] +//! [`dfs_find_path_where`]. //! //! [Breadth-first search]: https://en.wikipedia.org/wiki/Breadth-first_search //! [Depth-first search]: https://en.wikipedia.org/wiki/Depth-first_search @@ -52,17 +52,21 @@ impl Ord for DistanceOrderedVertex { } } -/// Return data type for [`dijkstra`] and [`dijkstra unweighted`]. +/// Return data type for [`dijkstra`] and [`dijkstra_unweighted`]. pub struct DijkstraResult { /// Vertex map of minimum distances from a given `source` vertex. pub distances: VertexMap>, - /// Vertex map of predecessors on some shortest path from a given `source` vertex. pub predecessors: VertexMap>, } // TODO: Generalize the return type of the weight function. -/// Dijkstra's algorithm with custom edge weights, returns minimum distances and predecessors. +/// [Dijkstra's algorithm] with custom edge weights, returns minimum distances and predecessors. +/// +/// Calculates the shortest paths from `source` to all vertices in `graph` with edge weights given +/// by `weight` function. Returns the distances from `source` to each vertex, and the predecessors +/// of each vertex on some shortest path from `source` to that vertex. Returns `None` for any vertex +/// not connected to `source`. /// /// # Panics /// @@ -85,6 +89,8 @@ pub struct DijkstraResult { /// assert_eq!(result.distances[target], Some(5)); /// assert_eq!(result.predecessors[target], Some(source)); /// ``` +/// +/// [Dijkstra's algorithm]: https://en.wikipedia.org/wiki/Dijkstra%27s_algorithm pub fn dijkstra(graph: &G, source: G::Vertex, weight: W) -> DijkstraResult where G: GraphTopology, @@ -100,7 +106,11 @@ where } } -/// Dijkstra's algorithm with custom edge weights, returns minimum distances. +/// [Dijkstra's algorithm] with custom edge weights, returns minimum distances. +/// +/// Calculates the shortest paths from `source` to all vertices in `graph` with edge weights given +/// by `weight` function. Returns the distances from `source` to each vertex. Returns `None` for any +/// vertex not connected to `source`. /// /// # Panics /// @@ -110,7 +120,7 @@ where /// /// ``` /// # use grapherity::prelude::*; -/// # use grapherity::algorithms::{dijkstra, dijkstra_distances}; +/// # use grapherity::algorithms::dijkstra_distances; /// # use grapherity::models::Graph; /// let mut graph = Graph::new(); /// let source = graph.add_vertex(); @@ -122,6 +132,8 @@ where /// let distances = dijkstra_distances(&graph, source, |e| weights[e]); /// assert_eq!(distances[target], Some(5)); /// ``` +/// +/// [Dijkstra's algorithm]: https://en.wikipedia.org/wiki/Dijkstra%27s_algorithm pub fn dijkstra_distances( graph: &G, source: G::Vertex, @@ -134,8 +146,13 @@ where dijkstra_impl(graph, source, weight, |_, _| {}) } -/// Dijkstra's algorithm with constant weights of *1* for all edges, returns minimum distances and -/// predecessors. +/// [Dijkstra's algorithm] with unit edge weights, returns minimum distances and predecessors. +/// +/// Calculates the shortest paths from `source` to all vertices in an unweighted `graph`. Returns +/// the distances from `source` to each vertex, and the predecessors of each vertex on some shortest +/// path from `source` to that vertex. Returns `None` for any vertex not connected to `source`. +/// +/// Prefer [`bfs`] for unweighted graphs, it has better time and space complexity. /// /// # Panics /// @@ -145,7 +162,7 @@ where /// /// ``` /// # use grapherity::prelude::*; -/// # use grapherity::algorithms::{dijkstra, dijkstra_unweighted}; +/// # use grapherity::algorithms::dijkstra_unweighted; /// # use grapherity::models::Graph; /// let mut graph = Graph::new(); /// let source = graph.add_vertex(); @@ -156,6 +173,8 @@ where /// assert_eq!(result.distances[target], Some(1)); /// assert_eq!(result.predecessors[target], Some(source)); /// ``` +/// +/// [Dijkstra's algorithm]: https://en.wikipedia.org/wiki/Dijkstra%27s_algorithm pub fn dijkstra_unweighted(graph: &G, source: G::Vertex) -> DijkstraResult where G: GraphTopology, @@ -163,7 +182,13 @@ where dijkstra(graph, source, |_| 1) } -/// Dijkstra's algorithm with constant weights of *1* for all edges, returns minimum distances. +/// [Dijkstra's algorithm] with unit edge weights, returns minimum distances. +/// +/// Calculates the shortest paths from `source` to all vertices in an unweighted `graph`. Returns +/// the distances from `source` to each vertex. Returns `None` for any vertex not connected to +/// `source`. +/// +/// Prefer [`bfs_distances`] for unweighted graphs, it has better time and space complexity. /// /// # Panics /// @@ -173,7 +198,7 @@ where /// /// ``` /// # use grapherity::prelude::*; -/// # use grapherity::algorithms::{dijkstra, dijkstra_distances_unweighted}; +/// # use grapherity::algorithms::dijkstra_distances_unweighted; /// # use grapherity::models::Graph; /// let mut graph = Graph::new(); /// let source = graph.add_vertex(); @@ -183,6 +208,8 @@ where /// let distances = dijkstra_distances_unweighted(&graph, source); /// assert_eq!(distances[target], Some(1)); /// ``` +/// +/// [Dijkstra's algorithm]: https://en.wikipedia.org/wiki/Dijkstra%27s_algorithm pub fn dijkstra_distances_unweighted( graph: &G, source: G::Vertex, @@ -233,11 +260,44 @@ where distances } +/// Return data type for [`bfs`]. pub struct BfsResult { + /// Vertex map of minimum distances from a given `source` vertex. pub distances: VertexMap>, + /// Vertex map of predecessors on some shortest path from a given `source` vertex. pub predecessors: VertexMap>, } +/// [Breadth-first search] traversal from `source`, returns distances and predecessors. +/// +/// Traverses vertices in `graph` starting from `source`, exploring all neighbors before descending +/// further. Returns the distances from `source` to each vertex, and the predecessors of each vertex +/// on some shortest path from `source` to that vertex. Returns `None` for any vertex not connected +/// to `source`. +/// +/// Time complexity is *O(|V| + |E|)*, space complexity is *O(|V|)*. +/// +/// # Panics +/// +/// Panics if `source` is not a valid vertex of `graph`. +/// +/// # Examples +/// +/// ``` +/// # use grapherity::prelude::*; +/// # use grapherity::algorithms::bfs; +/// # use grapherity::models::Graph; +/// let mut graph = Graph::new(); +/// let source = graph.add_vertex(); +/// let target = graph.add_vertex(); +/// graph.add_edge(source, target); +/// +/// let result = bfs(&graph, source); +/// assert_eq!(result.distances[target], Some(1)); +/// assert_eq!(result.predecessors[target], Some(source)); +/// ``` +/// +/// [Breadth-first search]: https://en.wikipedia.org/wiki/Breadth-first_search pub fn bfs(graph: &G, source: G::Vertex) -> BfsResult where G: GraphTopology, @@ -253,6 +313,34 @@ where } } +/// [Breadth-first search] traversal from `source`, returns distances. +/// +/// Traverses vertices in `graph` starting from `source`, exploring all neighbors before descending +/// further. Returns the distances from `source` to each vertex. Returns `None` for any vertex not +/// connected to `source`. +/// +/// Time complexity is *O(|V| + |E|)*, space complexity is *O(|V|)*. +/// +/// # Panics +/// +/// Panics if `source` is not a valid vertex of `graph`. +/// +/// # Examples +/// +/// ``` +/// # use grapherity::prelude::*; +/// # use grapherity::algorithms::bfs_distances; +/// # use grapherity::models::Graph; +/// let mut graph = Graph::new(); +/// let source = graph.add_vertex(); +/// let target = graph.add_vertex(); +/// graph.add_edge(source, target); +/// +/// let distances = bfs_distances(&graph, source); +/// assert_eq!(distances[target], Some(1)); +/// ``` +/// +/// [Breadth-first search]: https://en.wikipedia.org/wiki/Breadth-first_search pub fn bfs_distances(graph: &G, source: G::Vertex) -> VertexMap> where G: GraphTopology, @@ -260,6 +348,33 @@ where bfs_impl(graph, source, |_, _| true).distances } +/// [Breadth-first search] from `source` for `target`, returns the distance. +/// +/// Traverses vertices in `graph` starting from `source` until `target` is found, exploring all +/// neighbors before descending further. Returns the minimum distance from `source` to `target` if +/// `target` is a valid vertex of `graph` connected to `source`, or `None` otherwise. +/// +/// Time complexity is *O(|V| + |E|)*, space complexity is *O(|V|)*. +/// +/// # Panics +/// +/// Panics if `source` is not a valid vertex of `graph`. +/// +/// # Examples +/// +/// ``` +/// # use grapherity::prelude::*; +/// # use grapherity::algorithms::bfs_find; +/// # use grapherity::models::Graph; +/// let mut graph = Graph::new(); +/// let source = graph.add_vertex(); +/// let target = graph.add_vertex(); +/// graph.add_edge(source, target); +/// +/// assert_eq!(bfs_find(&graph, source, target), Some(1)); +/// ``` +/// +/// [Breadth-first search]: https://en.wikipedia.org/wiki/Breadth-first_search pub fn bfs_find(graph: &G, source: G::Vertex, target: G::Vertex) -> Option where G: GraphTopology, @@ -267,6 +382,35 @@ where bfs_find_where(graph, source, |v| v == target).map(|(_, distance)| distance) } +/// [Breadth-first search] from `source` for a vertex matching `predicate`, returns the vertex and +/// its distance. +/// +/// Traverses vertices in `graph` starting from `source` until a vertex satisfying `predicate` is +/// found, exploring all neighbors before descending further. Returns the first vertex satisfying +/// `predicate` and its minimum distance from `source`, or `None` if no such vertex is connected to +/// `source`. +/// +/// Time complexity is *O(|V| + |E|)*, space complexity is *O(|V|)*. +/// +/// # Panics +/// +/// Panics if `source` is not a valid vertex of `graph`. +/// +/// # Examples +/// +/// ``` +/// # use grapherity::prelude::*; +/// # use grapherity::algorithms::bfs_find_where; +/// # use grapherity::models::Graph; +/// let mut graph = Graph::new(); +/// let source = graph.add_vertex(); +/// let target = graph.add_vertex(); +/// graph.add_edge(source, target); +/// +/// assert_eq!(bfs_find_where(&graph, source, |v| v == target), Some((target, 1))); +/// ``` +/// +/// [Breadth-first search]: https://en.wikipedia.org/wiki/Breadth-first_search pub fn bfs_find_where(graph: &G, source: G::Vertex, predicate: P) -> Option<(G::Vertex, u32)> where G: GraphTopology, @@ -315,11 +459,44 @@ where } } +/// Return data type for [`dfs`]. pub struct DfsResult { + /// Vertex map indicating which vertices were visited during the search. pub visited: VertexMap, + /// Vertex map of predecessors on the DFS tree path from a given `source` vertex. pub predecessors: VertexMap>, } +/// [Depth-first search] traversal from `source`, returns visited vertices and predecessors. +/// +/// Traverses vertices in `graph` starting from `source`, exploring each branch as far as possible +/// before backtracking. Returns for each vertex whether it was visited, and the predecessors of +/// each vertex on the DFS tree path from `source` to that vertex. Any vertex not connected to +/// `source` is marked unvisited and has no predecessor. +/// +/// Time complexity is *O(|V| + |E|)*, space complexity is *O(|V|)*. +/// +/// # Panics +/// +/// Panics if `source` is not a valid vertex of `graph`. +/// +/// # Examples +/// +/// ``` +/// # use grapherity::prelude::*; +/// # use grapherity::algorithms::dfs; +/// # use grapherity::models::Graph; +/// let mut graph = Graph::new(); +/// let source = graph.add_vertex(); +/// let target = graph.add_vertex(); +/// graph.add_edge(source, target); +/// +/// let result = dfs(&graph, source); +/// assert!(result.visited[target]); +/// assert_eq!(result.predecessors[target], Some(source)); +/// ``` +/// +/// [Depth-first search]: https://en.wikipedia.org/wiki/Depth-first_search pub fn dfs(graph: &G, source: G::Vertex) -> DfsResult where G: GraphTopology, @@ -335,6 +512,34 @@ where } } +/// [Depth-first search] traversal from `source`, returns visited vertices. +/// +/// Traverses vertices in `graph` starting from `source`, exploring each branch as far as possible +/// before backtracking. Returns a map indicating which vertices were visited, i.e. which vertices +/// are connected to `source`. +/// +/// Time complexity is *O(|V| + |E|)*, space complexity is *O(|V|)*. +/// +/// # Panics +/// +/// Panics if `source` is not a valid vertex of `graph`. +/// +/// # Examples +/// +/// ``` +/// # use grapherity::prelude::*; +/// # use grapherity::algorithms::dfs_visited; +/// # use grapherity::models::Graph; +/// let mut graph = Graph::new(); +/// let source = graph.add_vertex(); +/// let target = graph.add_vertex(); +/// graph.add_edge(source, target); +/// +/// let visited = dfs_visited(&graph, source); +/// assert!(visited[target]); +/// ``` +/// +/// [Depth-first search]: https://en.wikipedia.org/wiki/Depth-first_search pub fn dfs_visited(graph: &G, source: G::Vertex) -> VertexMap where G: GraphTopology, @@ -342,6 +547,33 @@ where dfs_impl(graph, source, |_, _| true).visited } +/// [Depth-first search] from `source` for `target`, returns whether it was found. +/// +/// Traverses vertices in `graph` starting from `source` until `target` is found, exploring each +/// branch as far as possible before backtracking. Returns `true` if `target` is a valid vertex of +/// `graph` connected to `source`, or `false` otherwise. +/// +/// Time complexity is *O(|V| + |E|)*, space complexity is *O(|V|)*. +/// +/// # Panics +/// +/// Panics if `source` is not a valid vertex of `graph`. +/// +/// # Examples +/// +/// ``` +/// # use grapherity::prelude::*; +/// # use grapherity::algorithms::dfs_find; +/// # use grapherity::models::Graph; +/// let mut graph = Graph::new(); +/// let source = graph.add_vertex(); +/// let target = graph.add_vertex(); +/// graph.add_edge(source, target); +/// +/// assert!(dfs_find(&graph, source, target)); +/// ``` +/// +/// [Depth-first search]: https://en.wikipedia.org/wiki/Depth-first_search pub fn dfs_find(graph: &G, source: G::Vertex, target: G::Vertex) -> bool where G: GraphTopology, @@ -349,6 +581,33 @@ where dfs_find_where(graph, source, |v| v == target).is_some() } +/// [Depth-first search] from `source` for a vertex matching `predicate`, returns the vertex. +/// +/// Traverses vertices in `graph` starting from `source` until a vertex satisfying `predicate` is +/// found, exploring each branch as far as possible before backtracking. Returns the first vertex +/// satisfying `predicate`, or `None` if no such vertex is connected to `source`. +/// +/// Time complexity is *O(|V| + |E|)*, space complexity is *O(|V|)*. +/// +/// # Panics +/// +/// Panics if `source` is not a valid vertex of `graph`. +/// +/// # Examples +/// +/// ``` +/// # use grapherity::prelude::*; +/// # use grapherity::algorithms::dfs_find_where; +/// # use grapherity::models::Graph; +/// let mut graph = Graph::new(); +/// let source = graph.add_vertex(); +/// let target = graph.add_vertex(); +/// graph.add_edge(source, target); +/// +/// assert_eq!(dfs_find_where(&graph, source, |v| v == target), Some(target)); +/// ``` +/// +/// [Depth-first search]: https://en.wikipedia.org/wiki/Depth-first_search pub fn dfs_find_where(graph: &G, source: G::Vertex, predicate: P) -> Option where G: GraphTopology, @@ -396,6 +655,35 @@ where } } +/// [Depth-first search] from `source` for `target`, returns the path as a sequence of edges. +/// +/// Traverses vertices in `graph` starting from `source` until `target` is found, exploring each +/// branch as far as possible before backtracking. Returns some path from `source` to `target` as a +/// sequence of edges in traversal order if `target` is a valid vertex of `graph` connected to +/// `source`, or `None` otherwise. The returned path is empty if and only if `source` equals +/// `target`. +/// +/// Time complexity is *O(|V| + |E|)*, space complexity is *O(|V|)*. +/// +/// # Panics +/// +/// Panics if `source` is not a valid vertex of `graph`. +/// +/// # Examples +/// +/// ``` +/// # use grapherity::prelude::*; +/// # use grapherity::algorithms::dfs_find_path; +/// # use grapherity::models::Graph; +/// let mut graph = Graph::new(); +/// let source = graph.add_vertex(); +/// let target = graph.add_vertex(); +/// let e = graph.add_edge(source, target); +/// +/// assert_eq!(dfs_find_path(&graph, source, target), Some(vec![e])); +/// ``` +/// +/// [Depth-first search]: https://en.wikipedia.org/wiki/Depth-first_search pub fn dfs_find_path(graph: &G, source: G::Vertex, target: G::Vertex) -> Option> where G: GraphTopology, @@ -403,6 +691,36 @@ where dfs_find_path_where(graph, source, |v| v == target) } +/// [Depth-first search] from `source` for a vertex matching `predicate`, returns the path as a +/// sequence of edges. +/// +/// Traverses vertices in `graph` starting from `source` until a vertex satisfying `predicate` is +/// found, exploring each branch as far as possible before backtracking. Returns some path from +/// `source` to the first vertex satisfying `predicate` as a sequence of edges in traversal order, +/// or `None` if no such vertex is connected to `source`. The returned path is empty if and only if +/// `source` satisfies `predicate`. +/// +/// Time complexity is *O(|V| + |E|)*, space complexity is *O(|V|)*. +/// +/// # Panics +/// +/// Panics if `source` is not a valid vertex of `graph`. +/// +/// # Examples +/// +/// ``` +/// # use grapherity::prelude::*; +/// # use grapherity::algorithms::dfs_find_path_where; +/// # use grapherity::models::Graph; +/// let mut graph = Graph::new(); +/// let source = graph.add_vertex(); +/// let target = graph.add_vertex(); +/// let e = graph.add_edge(source, target); +/// +/// assert_eq!(dfs_find_path_where(&graph, source, |v| v == target), Some(vec![e])); +/// ``` +/// +/// [Depth-first search]: https://en.wikipedia.org/wiki/Depth-first_search pub fn dfs_find_path_where(graph: &G, source: G::Vertex, predicate: P) -> Option> where G: GraphTopology,