Skip to content

Commit

Permalink
graph: extract function that reverses graph edges
Browse files Browse the repository at this point in the history
ReverseGraphIterator will be inlined. It doesn't make sense the iterator yields
Item = Result<..> whereas all possible errors are confined by constructor.
  • Loading branch information
yuja committed Dec 23, 2024
1 parent 7bf31c1 commit d6b84da
Showing 1 changed file with 26 additions and 18 deletions.
44 changes: 26 additions & 18 deletions lib/src/graph.rs
Original file line number Diff line number Diff line change
Expand Up @@ -85,24 +85,7 @@ where
pub fn new(
input: impl Iterator<Item = Result<GraphNode<N>, RevsetEvaluationError>>,
) -> Result<Self, RevsetEvaluationError> {
let mut entries = vec![];
let mut reverse_edges: HashMap<N, Vec<GraphEdge<N>>> = HashMap::new();
for item in input {
let (node, edges) = item?;
for GraphEdge { target, edge_type } in edges {
reverse_edges.entry(target).or_default().push(GraphEdge {
target: node.clone(),
edge_type,
});
}
entries.push(node);
}

let mut items = vec![];
for node in entries.into_iter() {
let edges = reverse_edges.get(&node).cloned().unwrap_or_default();
items.push((node, edges));
}
let items = reverse_graph(input)?;
Ok(Self { items })
}
}
Expand All @@ -115,6 +98,31 @@ impl<N> Iterator for ReverseGraphIterator<N> {
}
}

/// Creates new graph in which edges are reversed.
fn reverse_graph<N: Clone + Eq + Hash, E>(
input: impl Iterator<Item = Result<GraphNode<N>, E>>,
) -> Result<Vec<GraphNode<N>>, E> {
let mut entries = vec![];
let mut reverse_edges: HashMap<N, Vec<GraphEdge<N>>> = HashMap::new();
for item in input {
let (node, edges) = item?;
for GraphEdge { target, edge_type } in edges {
reverse_edges.entry(target).or_default().push(GraphEdge {
target: node.clone(),
edge_type,
});
}
entries.push(node);
}

let mut items = vec![];
for node in entries.into_iter() {
let edges = reverse_edges.get(&node).cloned().unwrap_or_default();
items.push((node, edges));
}
Ok(items)
}

/// Graph iterator adapter to group topological branches.
///
/// Basic idea is DFS from the heads. At fork point, the other descendant
Expand Down

0 comments on commit d6b84da

Please sign in to comment.