graph_algorithms/
lib.rs

1#![forbid(unsafe_code)]
2
3use std::{error::Error, fmt};
4
5#[cfg(feature = "bellman_ford")]
6pub mod bellman_ford;
7pub use bellman_ford::*;
8
9#[cfg(feature = "dijkstra")]
10pub mod dijkstra;
11pub use dijkstra::*;
12
13#[cfg(feature = "floyd_warshall")]
14pub mod floyd_warshall;
15pub use floyd_warshall::*;
16
17/// Error type for graph algorithms.
18#[derive(Debug, Clone, PartialEq, Eq)]
19pub enum GraphError {
20    /// Graph contains a negative weight cycle.
21    NegativeWeightCycle,
22
23    /// Graph does not contain a start node.
24    MissingStartNode,
25}
26
27impl Error for GraphError {}
28
29impl fmt::Display for GraphError {
30    /// Display the error message.
31    ///
32    /// # Arguments
33    ///
34    /// - `f`: Formatter.
35    ///
36    /// # Returns
37    ///
38    /// Result containing the formatted error message.
39    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
40        write!(f, "{:?}", self)
41    }
42}
43
44/// A trait for graph search algorithms.
45pub trait GraphAlgorithm {
46    /// Type of node.
47    type Node;
48
49    /// Type of weight.
50    type Weight;
51
52    /// Run the graph algorithm.
53    ///
54    /// # Arguments
55    ///
56    /// - `start`: Starting node, if applicable.
57    ///
58    /// # Returns
59    ///
60    /// Result containing the weight of the shortest path, or an error.
61    fn run(&self, start: Option<Self::Node>) -> Result<Self::Weight, GraphError>;
62}
63
64#[cfg(test)]
65mod tests {
66    use super::*;
67
68    #[test]
69    fn test_graph_error() {
70        assert_eq!(
71            format!("{}", GraphError::NegativeWeightCycle),
72            "NegativeWeightCycle"
73        );
74
75        assert_eq!(
76            format!("{}", GraphError::MissingStartNode),
77            "MissingStartNode"
78        );
79    }
80}