about summary refs log tree commit diff
path: root/src/libstd
diff options
context:
space:
mode:
authorPiotr Czarnecki <pioczarn@gmail.com>2014-11-08 17:26:52 +0100
committerPiotr Czarnecki <pioczarn@gmail.com>2014-11-30 22:52:11 +0100
commitb82624bf205e83555d7764d9f849fbfd30df0083 (patch)
treedfaae7120f480c9acb4fb876f821b5ce748a9b6a /src/libstd
parent72c96badd277f1090d7a70fdca37b547b6ba000f (diff)
downloadrust-b82624bf205e83555d7764d9f849fbfd30df0083.tar.gz
rust-b82624bf205e83555d7764d9f849fbfd30df0083.zip
std: Change the behavior of `reserve` for HashMap.
HashMap's `reserve` method now takes as an argument the *extra* space
to reserve.

[breaking-change]
Diffstat (limited to 'src/libstd')
-rw-r--r--src/libstd/collections/hash/map.rs23
1 files changed, 17 insertions, 6 deletions
diff --git a/src/libstd/collections/hash/map.rs b/src/libstd/collections/hash/map.rs
index f0b1ae9f1bb..17e6becdfaf 100644
--- a/src/libstd/collections/hash/map.rs
+++ b/src/libstd/collections/hash/map.rs
@@ -587,9 +587,13 @@ impl<K: Eq + Hash<S>, V, S, H: Hasher<S>> HashMap<K, V, H> {
         self.resize_policy.usable_capacity(self.table.capacity())
     }
 
+    /// Reserves capacity for at least `additional` more elements to be inserted
+    /// in the `HashMap`. The collection may reserve more space to avoid
+    /// frequent reallocations.
     ///
-    /// This function has no effect on the operational semantics of the
-    /// hashtable, only on performance.
+    /// # Panics
+    ///
+    /// Panics if the new allocation size overflows `uint`.
     ///
     /// # Example
     ///
@@ -598,11 +602,18 @@ impl<K: Eq + Hash<S>, V, S, H: Hasher<S>> HashMap<K, V, H> {
     /// let mut map: HashMap<&str, int> = HashMap::new();
     /// map.reserve(10);
     /// ```
-    pub fn reserve(&mut self, new_minimum_capacity: uint) {
-        let cap = max(INITIAL_CAPACITY, new_minimum_capacity).next_power_of_two();
+    #[unstable = "matches collection reform specification, waiting for dust to settle"]
+    pub fn reserve(&mut self, additional: uint) {
+        let new_size = self.len().checked_add(additional).expect("capacity overflow");
+        let min_cap = self.resize_policy.min_capacity(new_size);
+
+        // An invalid value shouldn't make us run out of space. This includes
+        // an overflow check.
+        assert!(new_size <= min_cap);
 
-        if self.table.capacity() < cap {
-            self.resize(cap);
+        if self.table.capacity() < min_cap {
+            let new_capacity = max(min_cap.next_power_of_two(), INITIAL_CAPACITY);
+            self.resize(new_capacity);
         }
     }