From 607d2973da7bd5895a5e84a65ba5174527bee904 Mon Sep 17 00:00:00 2001 From: Nicholas Nethercote Date: Mon, 3 Oct 2016 14:31:30 +1100 Subject: [PATCH] Avoid overflow check in `HashMap::reserve`'s fast path. --- src/libstd/collections/hash/map.rs | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/libstd/collections/hash/map.rs b/src/libstd/collections/hash/map.rs index 5fdc6056c68f..e8ca2977241e 100644 --- a/src/libstd/collections/hash/map.rs +++ b/src/libstd/collections/hash/map.rs @@ -667,8 +667,9 @@ impl HashMap /// ``` #[stable(feature = "rust1", since = "1.0.0")] pub fn reserve(&mut self, additional: usize) { - let min_cap = self.len().checked_add(additional).expect("reserve overflow"); - if self.capacity() < min_cap { + let remaining = self.capacity() - self.len(); // this can't overflow + if remaining < additional { + let min_cap = self.len().checked_add(additional).expect("reserve overflow"); let raw_cap = self.resize_policy.raw_capacity(min_cap); self.resize(raw_cap); }