@@ -587,9 +587,13 @@ impl<K: Eq + Hash<S>, V, S, H: Hasher<S>> HashMap<K, V, H> {
587587 self . resize_policy . usable_capacity ( self . table . capacity ( ) )
588588 }
589589
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.
590593 ///
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`.
593597 ///
594598 /// # Example
595599 ///
@@ -598,11 +602,18 @@ impl<K: Eq + Hash<S>, V, S, H: Hasher<S>> HashMap<K, V, H> {
598602 /// let mut map: HashMap<&str, int> = HashMap::new();
599603 /// map.reserve(10);
600604 /// ```
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) ;
603613
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) ;
606617 }
607618 }
608619
0 commit comments