@@ -400,6 +400,17 @@ impl<T: fmt::Debug> fmt::Debug for BinaryHeap<T> {
400400 }
401401}
402402
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+
403414impl < T : Ord > BinaryHeap < T > {
404415 /// Creates an empty `BinaryHeap` as a max-heap.
405416 ///
@@ -851,30 +862,19 @@ impl<T: Ord> BinaryHeap<T> {
851862 where
852863 F : FnMut ( & T ) -> bool ,
853864 {
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 } ;
861868 let mut i = 0 ;
869+
862870 guard. heap . data . retain ( |e| {
863871 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;
866874 }
867875 i += 1 ;
868876 keep
869877 } ) ;
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- }
878878 }
879879}
880880
0 commit comments