@@ -182,12 +182,14 @@ impl<N, E, Ix = DefIndex> Dag<N, E, Ix> where Ix: IndexType {
182
182
pub fn add_edge ( & mut self , a : NodeIndex < Ix > , b : NodeIndex < Ix > , weight : E )
183
183
-> Result < EdgeIndex < Ix > , WouldCycle < E > >
184
184
{
185
+ let should_check_for_cycle = must_check_for_cycle ( self , a, b) ;
186
+
185
187
let idx = self . graph . add_edge ( a, b, weight) ;
186
188
187
189
// Check if adding the edge has created a cycle.
188
190
//
189
191
// 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 ) {
191
193
let weight = self . graph . remove_edge ( idx) . expect ( "No edge for index" ) ;
192
194
Err ( WouldCycle ( weight) )
193
195
@@ -235,15 +237,14 @@ impl<N, E, Ix = DefIndex> Dag<N, E, Ix> where Ix: IndexType {
235
237
let mut should_check_for_cycle = false ;
236
238
237
239
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.
241
241
if !should_check_for_cycle {
242
- if must_check_for_cycle ( self , a, b, idx ) {
242
+ if must_check_for_cycle ( self , a, b) {
243
243
should_check_for_cycle = true ;
244
244
}
245
245
}
246
246
247
+ self . graph . add_edge ( a, b, weight) ;
247
248
num_edges += 1 ;
248
249
}
249
250
@@ -485,14 +486,11 @@ impl<N, E, Ix = DefIndex> Dag<N, E, Ix> where Ix: IndexType {
485
486
///
486
487
/// If our parent *a* has no parents or our child *b* has no children, or if there was already an
487
488
/// 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
492
490
where Ix : IndexType ,
493
491
{
494
492
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 ( )
496
494
}
497
495
498
496
0 commit comments