Skip to main content

netoptim_rs/
error.rs

1//! Error types for netoptim-rs
2
3use std::fmt;
4
5/// Error types for network optimization algorithms
6#[derive(Debug, Clone, PartialEq)]
7pub enum NetOptimError {
8    /// Negative edge weight found where non-negative weights are required
9    NegativeWeight,
10    /// Negative cycle detected in the graph
11    NegativeCycle,
12    /// No path exists between nodes
13    NoPath,
14    /// Invalid node index
15    InvalidNode,
16    /// Graph is empty
17    EmptyGraph,
18    /// Algorithm-specific error with message
19    AlgorithmError(String),
20}
21
22impl fmt::Display for NetOptimError {
23    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
24        match self {
25            NetOptimError::NegativeWeight => {
26                write!(
27                    f,
28                    "Negative edge weight found where non-negative weights are required"
29                )
30            }
31            NetOptimError::NegativeCycle => {
32                write!(f, "Negative cycle detected in the graph")
33            }
34            NetOptimError::NoPath => {
35                write!(f, "No path exists between the specified nodes")
36            }
37            NetOptimError::InvalidNode => {
38                write!(f, "Invalid node index provided")
39            }
40            NetOptimError::EmptyGraph => {
41                write!(f, "Graph is empty")
42            }
43            NetOptimError::AlgorithmError(msg) => {
44                write!(f, "Algorithm error: {}", msg)
45            }
46        }
47    }
48}
49
50impl std::error::Error for NetOptimError {}
51
52#[cfg(test)]
53mod tests {
54    use super::*;
55
56    #[test]
57    fn test_error_display() {
58        assert_eq!(
59            format!("{}", NetOptimError::NegativeWeight),
60            "Negative edge weight found where non-negative weights are required"
61        );
62        assert_eq!(
63            format!("{}", NetOptimError::NegativeCycle),
64            "Negative cycle detected in the graph"
65        );
66        assert_eq!(
67            format!("{}", NetOptimError::NoPath),
68            "No path exists between the specified nodes"
69        );
70        assert_eq!(
71            format!("{}", NetOptimError::InvalidNode),
72            "Invalid node index provided"
73        );
74        assert_eq!(format!("{}", NetOptimError::EmptyGraph), "Graph is empty");
75        assert_eq!(
76            format!("{}", NetOptimError::AlgorithmError("test".to_string())),
77            "Algorithm error: test"
78        );
79    }
80
81    #[test]
82    fn test_error_equality() {
83        assert_eq!(NetOptimError::NegativeWeight, NetOptimError::NegativeWeight);
84        assert_eq!(NetOptimError::NegativeCycle, NetOptimError::NegativeCycle);
85        assert_ne!(NetOptimError::NegativeWeight, NetOptimError::NegativeCycle);
86    }
87}