Skip to main content

god_gragh/
errors.rs

1//! 图操作错误类型定义
2//!
3//! 提供详细的错误类型,支持错误链和上下文信息
4
5use core::fmt;
6use core::fmt::{Display, Formatter};
7
8/// 图操作结果类型别名
9pub type GraphResult<T> = Result<T, GraphError>;
10
11/// 图操作错误类型
12#[derive(Debug, Clone, PartialEq)]
13pub enum GraphError {
14    /// 节点不存在:索引无效或超出范围
15    NodeNotFound {
16        /// 导致错误的节点索引
17        index: usize,
18    },
19
20    /// 节点已删除:generation 不匹配
21    NodeDeleted {
22        /// 导致错误的节点索引
23        index: usize,
24        /// 提供的 generation
25        provided: u32,
26        /// 当前的 generation
27        current: u32,
28    },
29
30    /// 边不存在:索引无效或超出范围
31    EdgeNotFound {
32        /// 导致错误的边索引
33        index: usize,
34    },
35
36    /// 边已删除:generation 不匹配
37    EdgeDeleted {
38        /// 导致错误的边索引
39        index: usize,
40        /// 提供的 generation
41        provided: u32,
42        /// 当前的 generation
43        current: u32,
44    },
45
46    /// 边已存在:简单图不允许重边
47    EdgeAlreadyExists {
48        /// 源节点索引
49        from: usize,
50        /// 目标节点索引
51        to: usize,
52    },
53
54    /// 不允许自环
55    SelfLoopNotAllowed {
56        /// 节点索引
57        node: usize,
58    },
59
60    /// 超过最大节点容量
61    GraphCapacityExceeded {
62        /// 当前数量
63        current: usize,
64        /// 最大容量
65        max: usize,
66    },
67
68    /// 内存分配失败
69    MemoryAllocationFailed {
70        /// 请求的大小(字节)
71        requested: usize,
72    },
73
74    /// 无效的图方向操作
75    InvalidDirection,
76
77    /// 图不是有向图
78    GraphNotDirected,
79
80    /// 图不是无向图
81    GraphNotUndirected,
82
83    /// 图中存在环(用于 DAG 操作)
84    GraphHasCycle,
85
86    /// 算法不收敛
87    AlgorithmNotConverged {
88        /// 执行的迭代次数
89        iterations: usize,
90        /// 最终误差
91        error: f64,
92    },
93
94    /// 负权环检测到(Bellman-Ford)
95    NegativeCycle,
96
97    /// 负权重边检测到(Dijkstra 不支持)
98    NegativeWeight {
99        /// 源节点索引
100        from: usize,
101        /// 目标节点索引
102        to: usize,
103        /// 权重值
104        weight: f64,
105    },
106
107    /// 索引越界
108    IndexOutOfBounds {
109        /// 提供的索引
110        index: usize,
111        /// 边界
112        bound: usize,
113    },
114}
115
116impl Display for GraphError {
117    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
118        match self {
119            GraphError::NodeNotFound { index } => {
120                write!(f, "节点不存在:索引 {} 无效或超出范围", index)
121            }
122            GraphError::NodeDeleted { index, provided, current } => {
123                write!(
124                    f,
125                    "节点已删除:索引 {} 的 generation 不匹配 (provided: {}, current: {})",
126                    index, provided, current
127                )
128            }
129            GraphError::EdgeNotFound { index } => {
130                write!(f, "边不存在:索引 {} 无效或超出范围", index)
131            }
132            GraphError::EdgeDeleted { index, provided, current } => {
133                write!(
134                    f,
135                    "边已删除:索引 {} 的 generation 不匹配 (provided: {}, current: {})",
136                    index, provided, current
137                )
138            }
139            GraphError::EdgeAlreadyExists { from, to } => {
140                write!(f, "边已存在:从节点 {} 到节点 {} 的边已存在", from, to)
141            }
142            GraphError::SelfLoopNotAllowed { node } => {
143                write!(f, "不允许自环:节点 {} 不能作为自身的边端点", node)
144            }
145            GraphError::GraphCapacityExceeded { current, max } => {
146                write!(
147                    f,
148                    "超过最大容量:当前 {},最大 {}",
149                    current, max
150                )
151            }
152            GraphError::MemoryAllocationFailed { requested } => {
153                write!(f, "内存分配失败:请求 {} 字节", requested)
154            }
155            GraphError::InvalidDirection => {
156                write!(f, "无效的图方向操作")
157            }
158            GraphError::GraphNotDirected => {
159                write!(f, "图不是有向图")
160            }
161            GraphError::GraphNotUndirected => {
162                write!(f, "图不是无向图")
163            }
164            GraphError::GraphHasCycle => {
165                write!(f, "图中存在环")
166            }
167            GraphError::AlgorithmNotConverged { iterations, error } => {
168                write!(
169                    f,
170                    "算法不收敛:执行 {} 次迭代后误差为 {}",
171                    iterations, error
172                )
173            }
174            GraphError::NegativeCycle => {
175                write!(f, "检测到负权环")
176            }
177            GraphError::NegativeWeight { from, to, weight } => {
178                write!(
179                    f,
180                    "检测到负权重边:节点 {} 到 {} 的权重为 {}(Dijkstra 不支持负权重,建议使用 Bellman-Ford 算法)",
181                    from, to, weight
182                )
183            }
184            GraphError::IndexOutOfBounds { index, bound } => {
185                write!(f, "索引越界:索引 {} 超出边界 {}", index, bound)
186            }
187        }
188    }
189}
190
191#[cfg(feature = "std")]
192impl std::error::Error for GraphError {}
193
194impl From<GraphError> for String {
195    fn from(err: GraphError) -> Self {
196        err.to_string()
197    }
198}
199
200#[cfg(test)]
201mod tests {
202    use super::*;
203
204    #[test]
205    fn test_error_display() {
206        let err = GraphError::NodeNotFound { index: 42 };
207        assert!(err.to_string().contains("42"));
208
209        let err = GraphError::EdgeAlreadyExists { from: 1, to: 2 };
210        assert!(err.to_string().contains("1"));
211        assert!(err.to_string().contains("2"));
212    }
213}