@@ -587,9 +587,13 @@ impl<K: Eq + Hash<S>, V, S, H: Hasher<S>> HashMap<K, V, H> {
587
587
self . resize_policy . usable_capacity ( self . table . capacity ( ) )
588
588
}
589
589
590
+ /// Reserves capacity for at least `additional` more elements to be inserted
591
+ /// in the `HashMap`. The collection may reserve more space to avoid
592
+ /// frequent reallocations.
590
593
///
591
- /// This function has no effect on the operational semantics of the
592
- /// hashtable, only on performance.
594
+ /// # Panics
595
+ ///
596
+ /// Panics if the new allocation size overflows `uint`.
593
597
///
594
598
/// # Example
595
599
///
@@ -598,11 +602,18 @@ impl<K: Eq + Hash<S>, V, S, H: Hasher<S>> HashMap<K, V, H> {
598
602
/// let mut map: HashMap<&str, int> = HashMap::new();
599
603
/// map.reserve(10);
600
604
/// ```
601
- pub fn reserve ( & mut self , new_minimum_capacity : uint ) {
602
- let cap = max ( INITIAL_CAPACITY , new_minimum_capacity) . next_power_of_two ( ) ;
605
+ #[ unstable = "matches collection reform specification, waiting for dust to settle" ]
606
+ pub fn reserve ( & mut self , additional : uint ) {
607
+ let new_size = self . len ( ) . checked_add ( additional) . expect ( "capacity overflow" ) ;
608
+ let min_cap = self . resize_policy . min_capacity ( new_size) ;
609
+
610
+ // An invalid value shouldn't make us run out of space. This includes
611
+ // an overflow check.
612
+ assert ! ( new_size <= min_cap) ;
603
613
604
- if self . table . capacity ( ) < cap {
605
- self . resize ( cap) ;
614
+ if self . table . capacity ( ) < min_cap {
615
+ let new_capacity = max ( min_cap. next_power_of_two ( ) , INITIAL_CAPACITY ) ;
616
+ self . resize ( new_capacity) ;
606
617
}
607
618
}
608
619
0 commit comments