From 749e543a59128c4eae660c0fc5252748f1ee3d5a Mon Sep 17 00:00:00 2001 From: AlexanderIvrii Date: Thu, 5 Oct 2023 11:12:25 +0300 Subject: [PATCH 1/2] mapping is not possible when a node has no neighbors --- rustworkx-core/src/token_swapper.rs | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/rustworkx-core/src/token_swapper.rs b/rustworkx-core/src/token_swapper.rs index c60e31425d..064e0e4870 100644 --- a/rustworkx-core/src/token_swapper.rs +++ b/rustworkx-core/src/token_swapper.rs @@ -205,6 +205,16 @@ where } let id_node = self.rev_node_map[&node]; let id_token = self.rev_node_map[&tokens[&node]]; + + if self + .graph + .neighbors(id_node) + .collect::>() + .is_empty() + { + return Err(MapNotPossible {}); + } + for id_neighbor in self.graph.neighbors(id_node) { let neighbor = self.node_map[&id_neighbor]; let dist_neighbor: DictMap = dijkstra( @@ -705,4 +715,19 @@ mod test_token_swapper { Err(_) => (), }; } + + #[test] + fn test_edgeless_graph_fails() { + let mut g = petgraph::graph::UnGraph::<(), ()>::new_undirected(); + let a = g.add_node(()); + let b = g.add_node(()); + let c = g.add_node(()); + let d = g.add_node(()); + g.add_edge(c, d, ()); + let mapping = HashMap::from([(a, b), (b, a)]); + match token_swapper(&g, mapping, Some(10), Some(4), Some(50)) { + Ok(_) => panic!("This should error"), + Err(_) => (), + }; + } } From d682b9ba5198e7a1d4c371fb494c41123cbab18b Mon Sep 17 00:00:00 2001 From: AlexanderIvrii Date: Fri, 6 Oct 2023 08:59:50 +0300 Subject: [PATCH 2/2] suggested improvement --- rustworkx-core/src/token_swapper.rs | 7 +------ 1 file changed, 1 insertion(+), 6 deletions(-) diff --git a/rustworkx-core/src/token_swapper.rs b/rustworkx-core/src/token_swapper.rs index 064e0e4870..8e30e9a76e 100644 --- a/rustworkx-core/src/token_swapper.rs +++ b/rustworkx-core/src/token_swapper.rs @@ -206,12 +206,7 @@ where let id_node = self.rev_node_map[&node]; let id_token = self.rev_node_map[&tokens[&node]]; - if self - .graph - .neighbors(id_node) - .collect::>() - .is_empty() - { + if self.graph.neighbors(id_node).next().is_none() { return Err(MapNotPossible {}); }