Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add reverse method to StableGraph #533

Merged
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
30 changes: 30 additions & 0 deletions src/graph_impl/stable_graph/mod.rs
Expand Up @@ -197,6 +197,20 @@ where
self.g.capacity()
}

/// Reverse the direction of all edges
pub fn reverse(&mut self) {
// swap edge endpoints,
// edge incoming / outgoing lists,
// node incoming / outgoing lists
for edge in &mut self.g.edges {
edge.node.swap(0, 1);
edge.next.swap(0, 1);
}
for node in &mut self.g.nodes {
node.next.swap(0, 1);
}
}

/// Remove all nodes and edges
pub fn clear(&mut self) {
self.node_count = 0;
Expand Down Expand Up @@ -2022,3 +2036,19 @@ fn extend_with_edges() {
assert_eq!(gr.edge_count(), 2);
gr.check_free_lists();
}

#[test]
fn test_reverse() {
let mut gr = StableGraph::<_, _>::default();
let a = gr.add_node("a");
let b = gr.add_node("b");

gr.add_edge(a, b, 0);

let mut reversed_gr = gr.clone();
reversed_gr.reverse();

for i in gr.node_indices() {
itertools::assert_equal(gr.edges_directed(i, Incoming), reversed_gr.edges(i));
}
}