]> git.lizzy.rs Git - rust.git/commitdiff
Ensure capacity returned of HashMap is max(capacity, length).
authorRyan Thomas <ryan@ryant.org>
Tue, 2 Feb 2016 06:15:27 +0000 (17:15 +1100)
committerRyan Thomas <ryan@ryant.org>
Tue, 2 Feb 2016 06:17:24 +0000 (17:17 +1100)
r? @Gankro

src/libstd/collections/hash/map.rs

index 173214eda44c79ecf5e6fb6199e5025d860b0bfa..7ce4aa07b50e8a1a7deeae51ab6152327c45be57 100644 (file)
@@ -72,7 +72,10 @@ fn usable_capacity(&self, cap: usize) -> usize {
         //
         // This doesn't have to be checked for overflow since allocation size
         // in bytes will overflow earlier than multiplication by 10.
-        cap * 10 / 11
+        //
+        // As per https://github.com/rust-lang/rust/pull/30991 this is updated
+        // to be: (cap * den + den - 1) / num
+        (cap * 10 + 10 - 1) / 11
     }
 }
 
@@ -2418,4 +2421,29 @@ fn test_extend_ref() {
         assert_eq!(a[&2], "two");
         assert_eq!(a[&3], "three");
     }
+
+    #[test]
+    fn test_capacity_not_less_than_len() {
+        let mut a = HashMap::new();
+        let mut item = 0;
+
+        for _ in 0..116 {
+            a.insert(item, 0);
+            item += 1;
+        }
+
+        assert!(a.capacity() > a.len());
+
+        let free = a.capacity() - a.len();
+        for _ in 0..free {
+            a.insert(item, 0);
+            item += 1;
+        }
+
+        assert_eq!(a.len(), a.capacity());
+
+        // Insert at capacity should cause allocation.
+        a.insert(item, 0);
+        assert!(a.capacity() > a.len());
+    }
 }