@@ -786,12 +786,11 @@ mod doublepq_tests {
786786 assert_eq ! ( pq. pop_max( ) , Some ( ( "b" , 20 ) ) ) ;
787787
788788 /*
789- As expected, this does not compile
789+ // As expected, this does not compile
790790 let iter_mut = pq.iter_mut();
791- iter_mut.for_each(|(_, p)| {*p += 2});
792791
793- assert_eq!(pq.pop_max(), Some(("f ", 9 )));
794- */
792+ assert_eq!(pq.pop_max(), Some(("a ", 21 )));
793+ iter_mut.for_each(|(_, p)| {*p += 2}); */
795794 }
796795
797796 #[ test]
@@ -819,7 +818,6 @@ mod doublepq_tests {
819818 pq. push ( Animal :: new ( "bird" . to_string ( ) , true , false ) , 7 ) ;
820819 pq. push ( Animal :: new ( "fish" . to_string ( ) , false , true ) , 4 ) ;
821820 pq. push ( Animal :: new ( "cow" . to_string ( ) , false , false ) , 3 ) ;
822-
823821 pq. retain ( |i, _| i. can_swim ) ;
824822
825823 assert_eq ! (
@@ -873,6 +871,71 @@ mod doublepq_tests {
873871 ) ;
874872 }
875873
874+ #[ test]
875+ fn extract_if ( ) {
876+ #[ derive( Hash , PartialEq , Eq , Debug ) ]
877+ struct Animal {
878+ name : String ,
879+ can_fly : bool ,
880+ can_swim : bool ,
881+ }
882+
883+ impl Animal {
884+ pub fn new ( name : String , can_fly : bool , can_swim : bool ) -> Self {
885+ Animal {
886+ name,
887+ can_fly,
888+ can_swim,
889+ }
890+ }
891+ }
892+
893+ let mut pq = DoublePriorityQueue :: new ( ) ;
894+ pq. push ( Animal :: new ( "dog" . to_string ( ) , false , true ) , 1 ) ;
895+ pq. push ( Animal :: new ( "cat" . to_string ( ) , false , false ) , 2 ) ;
896+ pq. push ( Animal :: new ( "bird" . to_string ( ) , true , false ) , 7 ) ;
897+ pq. push ( Animal :: new ( "fish" . to_string ( ) , false , true ) , 4 ) ;
898+ pq. push ( Animal :: new ( "cow" . to_string ( ) , false , false ) , 3 ) ;
899+
900+ let swimming_animals: Vec < ( Animal , i32 ) > = pq
901+ . extract_if ( |i, p| {
902+ if i. can_fly {
903+ * p -= 18 ;
904+ return false ;
905+ }
906+
907+ i. can_swim
908+ } )
909+ . collect ( ) ;
910+
911+ assert_eq ! (
912+ swimming_animals,
913+ [
914+ ( Animal :: new( "dog" . to_string( ) , false , true ) , 1 ) ,
915+ ( Animal :: new( "fish" . to_string( ) , false , true ) , 4 )
916+ ]
917+ ) ;
918+ assert_eq ! (
919+ pq. pop_max( ) ,
920+ Some ( ( Animal :: new( "cow" . to_string( ) , false , false ) , 3 ) )
921+ ) ;
922+ assert_eq ! (
923+ pq. pop_max( ) ,
924+ Some ( ( Animal :: new( "cat" . to_string( ) , false , false ) , 2 ) )
925+ ) ;
926+ assert_eq ! (
927+ pq. pop_max( ) ,
928+ Some ( ( Animal :: new( "bird" . to_string( ) , true , false ) , -11 ) )
929+ ) ;
930+
931+ /*
932+ // As expected, this does not compile
933+ let extract_if = pq.extract_if(|i, p| { i.can_fly });
934+
935+ assert_eq!(pq.pop_max(), None);
936+ extract_if.for_each(|(_, p)| println!("{:?}", p)); */
937+ }
938+
876939 #[ test]
877940 fn into_sorted_iter ( ) {
878941 let mut pq = DoublePriorityQueue :: new ( ) ;
0 commit comments