@@ -910,6 +910,46 @@ impl<K, V, S> HashMap<K, V, S>
910
910
}
911
911
}
912
912
913
+ /// Shrinks the capacity of the map with a lower limit. It will drop
914
+ /// down no lower than the supplied limit while maintaining the internal rules
915
+ /// and possibly leaving some space in accordance with the resize policy.
916
+ ///
917
+ /// Panics if the current capacity is smaller than the supplied
918
+ /// minimum capacity.
919
+ ///
920
+ /// # Examples
921
+ ///
922
+ /// ```
923
+ /// #![feature(shrink_to)]
924
+ /// use std::collections::HashMap;
925
+ ///
926
+ /// let mut map: HashMap<i32, i32> = HashMap::with_capacity(100);
927
+ /// map.insert(1, 2);
928
+ /// map.insert(3, 4);
929
+ /// assert!(map.capacity() >= 100);
930
+ /// map.shrink_to(10);
931
+ /// assert!(map.capacity() >= 10);
932
+ /// map.shrink_to(0);
933
+ /// assert!(map.capacity() >= 2);
934
+ /// ```
935
+ #[ unstable( feature = "shrink_to" , reason = "new API" , issue="0" ) ]
936
+ pub fn shrink_to ( & mut self , min_capacity : usize ) {
937
+ assert ! ( self . capacity( ) >= min_capacity, "Tried to shrink to a larger capacity" ) ;
938
+
939
+ let new_raw_cap = self . resize_policy . raw_capacity ( max ( self . len ( ) , min_capacity) ) ;
940
+ if self . raw_capacity ( ) != new_raw_cap {
941
+ let old_table = replace ( & mut self . table , RawTable :: new ( new_raw_cap) ) ;
942
+ let old_size = old_table. size ( ) ;
943
+
944
+ // Shrink the table. Naive algorithm for resizing:
945
+ for ( h, k, v) in old_table. into_iter ( ) {
946
+ self . insert_hashed_nocheck ( h, k, v) ;
947
+ }
948
+
949
+ debug_assert_eq ! ( self . table. size( ) , old_size) ;
950
+ }
951
+ }
952
+
913
953
/// Insert a pre-hashed key-value pair, without first checking
914
954
/// that there's enough room in the buckets. Returns a reference to the
915
955
/// newly insert value.
0 commit comments