@@ -400,6 +400,17 @@ impl<T: fmt::Debug> fmt::Debug for BinaryHeap<T> {
400
400
}
401
401
}
402
402
403
+ struct RebuildOnDrop < ' a , T : Ord > {
404
+ heap : & ' a mut BinaryHeap < T > ,
405
+ rebuild_from : usize ,
406
+ }
407
+
408
+ impl < ' a , T : Ord > Drop for RebuildOnDrop < ' a , T > {
409
+ fn drop ( & mut self ) {
410
+ self . heap . rebuild_tail ( self . rebuild_from ) ;
411
+ }
412
+ }
413
+
403
414
impl < T : Ord > BinaryHeap < T > {
404
415
/// Creates an empty `BinaryHeap` as a max-heap.
405
416
///
@@ -851,30 +862,19 @@ impl<T: Ord> BinaryHeap<T> {
851
862
where
852
863
F : FnMut ( & T ) -> bool ,
853
864
{
854
- struct RebuildOnDrop < ' a , T : Ord > {
855
- heap : & ' a mut BinaryHeap < T > ,
856
- first_removed : usize ,
857
- }
858
-
859
- let mut guard = RebuildOnDrop { first_removed : self . len ( ) , heap : self } ;
860
-
865
+ // rebuild_start will be updated to the first touched element below, and the rebuild will
866
+ // only be done for the tail.
867
+ let mut guard = RebuildOnDrop { rebuild_from : self . len ( ) , heap : self } ;
861
868
let mut i = 0 ;
869
+
862
870
guard. heap . data . retain ( |e| {
863
871
let keep = f ( e) ;
864
- if !keep && i < guard. first_removed {
865
- guard. first_removed = i;
872
+ if !keep && i < guard. rebuild_from {
873
+ guard. rebuild_from = i;
866
874
}
867
875
i += 1 ;
868
876
keep
869
877
} ) ;
870
-
871
- impl < ' a , T : Ord > Drop for RebuildOnDrop < ' a , T > {
872
- fn drop ( & mut self ) {
873
- // data[..first_removed] is untouched, so we only need to
874
- // rebuild the tail:
875
- self . heap . rebuild_tail ( self . first_removed ) ;
876
- }
877
- }
878
878
}
879
879
}
880
880
0 commit comments