graph: extract function that reverses graph edges

ReverseGraphIterator will be inlined. It doesn't make sense the iterator yields
Item = Result<..> whereas all possible errors are confined by constructor.
This commit is contained in:
Yuya Nishihara 2024-12-22 10:23:38 +09:00
parent 7bf31c1557
commit d6b84da382

View File

@ -85,6 +85,23 @@ where
pub fn new(
input: impl Iterator<Item = Result<GraphNode<N>, RevsetEvaluationError>>,
) -> Result<Self, RevsetEvaluationError> {
let items = reverse_graph(input)?;
Ok(Self { items })
}
}
impl<N> Iterator for ReverseGraphIterator<N> {
type Item = Result<GraphNode<N>, RevsetEvaluationError>;
fn next(&mut self) -> Option<Self::Item> {
self.items.pop().map(Ok)
}
}
/// 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 {
@ -103,16 +120,7 @@ where
let edges = reverse_edges.get(&node).cloned().unwrap_or_default();
items.push((node, edges));
}
Ok(Self { items })
}
}
impl<N> Iterator for ReverseGraphIterator<N> {
type Item = Result<GraphNode<N>, RevsetEvaluationError>;
fn next(&mut self) -> Option<Self::Item> {
self.items.pop().map(Ok)
}
Ok(items)
}
/// Graph iterator adapter to group topological branches.