Skip to content

Commit 1a23a6f

Browse files
committed
Add wrapper type ReversedGraph for swapping successors/predecessors
1 parent a48e7b0 commit 1a23a6f

File tree

2 files changed

+43
-0
lines changed

2 files changed

+43
-0
lines changed

compiler/rustc_data_structures/src/graph/mod.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ pub mod dominators;
44
pub mod implementation;
55
pub mod iterate;
66
mod reference;
7+
pub mod reversed;
78
pub mod scc;
89
pub mod vec_graph;
910

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
use crate::graph::{DirectedGraph, Predecessors, Successors};
2+
3+
/// View that reverses the direction of edges in its underlying graph, so that
4+
/// successors become predecessors and vice-versa.
5+
///
6+
/// Because of `impl<G: Graph> Graph for &G`, the underlying graph can be
7+
/// wrapped by-reference instead of by-value if desired.
8+
#[derive(Clone, Copy, Debug)]
9+
pub struct ReversedGraph<G> {
10+
pub inner: G,
11+
}
12+
13+
impl<G> ReversedGraph<G> {
14+
pub fn new(inner: G) -> Self {
15+
Self { inner }
16+
}
17+
}
18+
19+
impl<G: DirectedGraph> DirectedGraph for ReversedGraph<G> {
20+
type Node = G::Node;
21+
22+
fn num_nodes(&self) -> usize {
23+
self.inner.num_nodes()
24+
}
25+
}
26+
27+
// Implementing `StartNode` is not possible in general, because the start node
28+
// of an underlying graph is instead an _end_ node in the reversed graph.
29+
// But would be possible to define another wrapper type that adds an explicit
30+
// start node to its underlying graph, if desired.
31+
32+
impl<G: Predecessors> Successors for ReversedGraph<G> {
33+
fn successors(&self, node: Self::Node) -> impl Iterator<Item = Self::Node> {
34+
self.inner.predecessors(node)
35+
}
36+
}
37+
38+
impl<G: Successors> Predecessors for ReversedGraph<G> {
39+
fn predecessors(&self, node: Self::Node) -> impl Iterator<Item = Self::Node> {
40+
self.inner.successors(node)
41+
}
42+
}

0 commit comments

Comments
 (0)