From 9737c8714a33ae0e62ed49e4e0413d3d372dcd7b Mon Sep 17 00:00:00 2001 From: Julio Quintero Date: Thu, 7 Mar 2024 15:14:25 -0500 Subject: [PATCH] fix: dijkstra index out of boud --- .../fix-dijkstra-panic-3962ad36788cab00.yaml | 11 +++++ src/shortest_path/mod.rs | 43 +++++++++++++++++++ 2 files changed, 54 insertions(+) create mode 100644 releasenotes/notes/fix-dijkstra-panic-3962ad36788cab00.yaml diff --git a/releasenotes/notes/fix-dijkstra-panic-3962ad36788cab00.yaml b/releasenotes/notes/fix-dijkstra-panic-3962ad36788cab00.yaml new file mode 100644 index 0000000000..cf76a8e0d3 --- /dev/null +++ b/releasenotes/notes/fix-dijkstra-panic-3962ad36788cab00.yaml @@ -0,0 +1,11 @@ +--- +fixes: + - | + Fixed an issue with the Dijkstra path functions: + + * :func:`rustworkx.dijkstra_shortest_paths` + * :func:`rustworkx.dijkstra_shortest_path_lengths` + + where a `Pyo3.PanicException`were raise with no much detail at the moment + of pass in the `source` argument the index of an out of bound node. + Fixed `#1117 `__ diff --git a/src/shortest_path/mod.rs b/src/shortest_path/mod.rs index 959b1cbddb..4fb75dfeff 100644 --- a/src/shortest_path/mod.rs +++ b/src/shortest_path/mod.rs @@ -77,6 +77,17 @@ pub fn graph_dijkstra_shortest_paths( weight_fn: Option, default_weight: f64, ) -> PyResult { + if !graph + .node_indices() + .nodes + .iter() + .any(|&node| node == source) + { + return Err(PyIndexError::new_err(format!( + "Node source index \"{source}\" out of graph bound" + ))); + } + let start = NodeIndex::new(source); let goal_index: Option = target.map(NodeIndex::new); let mut paths: DictMap> = DictMap::with_capacity(graph.node_count()); @@ -216,6 +227,16 @@ pub fn digraph_dijkstra_shortest_paths( default_weight: f64, as_undirected: bool, ) -> PyResult { + if !graph + .node_indices() + .nodes + .iter() + .any(|&node| node == source) + { + return Err(PyIndexError::new_err(format!( + "Node source index \"{source}\" out of graph bound" + ))); + } let start = NodeIndex::new(source); let goal_index: Option = target.map(NodeIndex::new); let mut paths: DictMap> = DictMap::with_capacity(graph.node_count()); @@ -371,6 +392,17 @@ pub fn graph_dijkstra_shortest_path_lengths( edge_cost_fn: PyObject, goal: Option, ) -> PyResult { + if !graph + .node_indices() + .nodes + .iter() + .any(|&index| index == node) + { + return Err(PyIndexError::new_err(format!( + "Node source index \"{node}\" out of graph bound" + ))); + } + let edge_cost_callable = CostFn::from(edge_cost_fn); let start = NodeIndex::new(node); let goal_index: Option = goal.map(NodeIndex::new); @@ -440,6 +472,17 @@ pub fn digraph_dijkstra_shortest_path_lengths( edge_cost_fn: PyObject, goal: Option, ) -> PyResult { + if !graph + .node_indices() + .nodes + .iter() + .any(|&index| index == node) + { + return Err(PyIndexError::new_err(format!( + "Node source index \"{node}\" out of graph bound" + ))); + } + let edge_cost_callable = CostFn::from(edge_cost_fn); let start = NodeIndex::new(node);