Skip to content

Commit ed894ff

Browse files
committed
Refactor must_check_for_cycle for checking prior to adding the edge
1 parent 1607a40 commit ed894ff

File tree

1 file changed

+8
-10
lines changed

1 file changed

+8
-10
lines changed

src/lib.rs

Lines changed: 8 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -182,12 +182,14 @@ impl<N, E, Ix = DefIndex> Dag<N, E, Ix> where Ix: IndexType {
182182
pub fn add_edge(&mut self, a: NodeIndex<Ix>, b: NodeIndex<Ix>, weight: E)
183183
-> Result<EdgeIndex<Ix>, WouldCycle<E>>
184184
{
185+
let should_check_for_cycle = must_check_for_cycle(self, a, b);
186+
185187
let idx = self.graph.add_edge(a, b, weight);
186188

187189
// Check if adding the edge has created a cycle.
188190
//
189191
// TODO: Re-use a `pg::visit::Topo` for this. Perhaps store this in the `Dag` itself?
190-
if must_check_for_cycle(self, a, b, idx) && pg::algo::is_cyclic_directed(&self.graph) {
192+
if should_check_for_cycle && pg::algo::is_cyclic_directed(&self.graph) {
191193
let weight = self.graph.remove_edge(idx).expect("No edge for index");
192194
Err(WouldCycle(weight))
193195

@@ -235,15 +237,14 @@ impl<N, E, Ix = DefIndex> Dag<N, E, Ix> where Ix: IndexType {
235237
let mut should_check_for_cycle = false;
236238

237239
for (a, b, weight) in edges {
238-
let idx = self.graph.add_edge(a, b, weight);
239-
240-
// For every added edge, we must check whether or not we need to check for cycles.
240+
// Check whether or not we'll need to check for cycles.
241241
if !should_check_for_cycle {
242-
if must_check_for_cycle(self, a, b, idx) {
242+
if must_check_for_cycle(self, a, b) {
243243
should_check_for_cycle = true;
244244
}
245245
}
246246

247+
self.graph.add_edge(a, b, weight);
247248
num_edges += 1;
248249
}
249250

@@ -485,14 +486,11 @@ impl<N, E, Ix = DefIndex> Dag<N, E, Ix> where Ix: IndexType {
485486
///
486487
/// If our parent *a* has no parents or our child *b* has no children, or if there was already an
487488
/// edge connecting *a* to *b*, we know that adding this edge has not caused the graph to cycle.
488-
fn must_check_for_cycle<N, E, Ix>(dag: &Dag<N, E, Ix>,
489-
a: NodeIndex<Ix>,
490-
b: NodeIndex<Ix>,
491-
new_edge: EdgeIndex<Ix>) -> bool
489+
fn must_check_for_cycle<N, E, Ix>(dag: &Dag<N, E, Ix>, a: NodeIndex<Ix>, b: NodeIndex<Ix>) -> bool
492490
where Ix: IndexType,
493491
{
494492
dag.parents(a).next(dag).is_some() && dag.children(b).next(dag).is_some()
495-
&& !dag.children(a).any(dag, |_, e, n| n == b && e != new_edge)
493+
&& dag.find_edge(a, b).is_none()
496494
}
497495

498496

0 commit comments

Comments
 (0)