@@ -30,13 +30,30 @@ use std::convert::TryFrom;
3030
3131use hashbrown:: HashSet ;
3232
33- use pyo3:: exceptions:: PyTypeError ;
33+ use pyo3:: exceptions:: { PyIndexError , PyTypeError } ;
3434use pyo3:: prelude:: * ;
3535use pyo3:: Python ;
3636
3737use petgraph:: graph:: NodeIndex ;
38+ use petgraph:: EdgeType ;
3839
3940use crate :: iterators:: EdgeList ;
41+ use crate :: StablePyGraph ;
42+
43+ fn validate_source_nodes < Ty : EdgeType > (
44+ graph : & StablePyGraph < Ty > ,
45+ starts : & [ NodeIndex ] ,
46+ ) -> PyResult < ( ) > {
47+ for index in starts. iter ( ) {
48+ if !graph. contains_node ( * index) {
49+ return Err ( PyIndexError :: new_err ( format ! (
50+ "Node source index \" {}\" out of graph bound" ,
51+ index. index( )
52+ ) ) ) ;
53+ }
54+ }
55+ Ok ( ( ) )
56+ }
4057
4158/// Get an edge list of the tree edges from a depth-first traversal
4259///
@@ -386,6 +403,8 @@ pub fn digraph_bfs_search(
386403 None => graph. graph . node_indices ( ) . collect ( ) ,
387404 } ;
388405
406+ validate_source_nodes ( & graph. graph , & starts) ?;
407+
389408 breadth_first_search ( & graph. graph , starts, |event| {
390409 bfs_handler ( py, & visitor, event)
391410 } ) ?;
@@ -530,6 +549,8 @@ pub fn graph_bfs_search(
530549 None => graph. graph . node_indices ( ) . collect ( ) ,
531550 } ;
532551
552+ validate_source_nodes ( & graph. graph , & starts) ?;
553+
533554 breadth_first_search ( & graph. graph , starts, |event| {
534555 bfs_handler ( py, & visitor, event)
535556 } ) ?;
@@ -644,6 +665,8 @@ pub fn digraph_dfs_search(
644665 None => graph. graph . node_indices ( ) . collect ( ) ,
645666 } ;
646667
668+ validate_source_nodes ( & graph. graph , & starts) ?;
669+
647670 depth_first_search ( & graph. graph , starts, |event| {
648671 dfs_handler ( py, & visitor, event)
649672 } ) ?;
@@ -758,6 +781,8 @@ pub fn graph_dfs_search(
758781 None => graph. graph . node_indices ( ) . collect ( ) ,
759782 } ;
760783
784+ validate_source_nodes ( & graph. graph , & starts) ?;
785+
761786 depth_first_search ( & graph. graph , starts, |event| {
762787 dfs_handler ( py, & visitor, event)
763788 } ) ?;
@@ -895,6 +920,8 @@ pub fn digraph_dijkstra_search(
895920 None => graph. graph . node_indices ( ) . collect ( ) ,
896921 } ;
897922
923+ validate_source_nodes ( & graph. graph , & starts) ?;
924+
898925 let edge_cost_fn = CostFn :: try_from ( ( weight_fn, 1.0 ) ) ?;
899926 dijkstra_search (
900927 & graph. graph ,
@@ -1036,6 +1063,8 @@ pub fn graph_dijkstra_search(
10361063 None => graph. graph . node_indices ( ) . collect ( ) ,
10371064 } ;
10381065
1066+ validate_source_nodes ( & graph. graph , & starts) ?;
1067+
10391068 let edge_cost_fn = CostFn :: try_from ( ( weight_fn, 1.0 ) ) ?;
10401069 dijkstra_search (
10411070 & graph. graph ,
0 commit comments