about summary refs log tree commit diff
path: root/library/alloc/src/vec
diff options
context:
space:
mode:
authorThom Wiggers <thom@thomwiggers.nl>2021-01-24 13:29:39 +0100
committerThom Wiggers <thom@thomwiggers.nl>2021-01-26 19:25:37 +0100
commitd069c58e78891d453b0b17adfecd368694fd289f (patch)
tree097bcb7a715f4b3e38faf9a1e004405bb92669fd /library/alloc/src/vec
parent85e355ea9bd86ac6580a5d422a65dbf689845808 (diff)
downloadrust-d069c58e78891d453b0b17adfecd368694fd289f.tar.gz
rust-d069c58e78891d453b0b17adfecd368694fd289f.zip
shrink_to shouldn't panic on len greater than capacity
Diffstat (limited to 'library/alloc/src/vec')
-rw-r--r--library/alloc/src/vec/mod.rs12
1 files changed, 6 insertions, 6 deletions
diff --git a/library/alloc/src/vec/mod.rs b/library/alloc/src/vec/mod.rs
index b533ce79420..13fcf5207e0 100644
--- a/library/alloc/src/vec/mod.rs
+++ b/library/alloc/src/vec/mod.rs
@@ -321,7 +321,7 @@ mod spec_extend;
 /// ensures no unnecessary allocations or deallocations occur. Emptying a `Vec`
 /// and then filling it back up to the same [`len`] should incur no calls to
 /// the allocator. If you wish to free up unused memory, use
-/// [`shrink_to_fit`].
+/// [`shrink_to_fit`] or [`shrink_to`].
 ///
 /// [`push`] and [`insert`] will never (re)allocate if the reported capacity is
 /// sufficient. [`push`] and [`insert`] *will* (re)allocate if
@@ -360,6 +360,7 @@ mod spec_extend;
 /// [`String`]: crate::string::String
 /// [`&str`]: type@str
 /// [`shrink_to_fit`]: Vec::shrink_to_fit
+/// [`shrink_to`]: Vec::shrink_to
 /// [`capacity`]: Vec::capacity
 /// [`mem::size_of::<T>`]: core::mem::size_of
 /// [`len`]: Vec::len
@@ -909,10 +910,7 @@ impl<T, A: Allocator> Vec<T, A> {
     /// The capacity will remain at least as large as both the length
     /// and the supplied value.
     ///
-    /// # Panics
-    ///
-    /// Panics if the current capacity is smaller than the supplied
-    /// minimum capacity.
+    /// If the current capacity is less than the lower limit, this is a no-op.
     ///
     /// # Examples
     ///
@@ -929,7 +927,9 @@ impl<T, A: Allocator> Vec<T, A> {
     #[doc(alias = "realloc")]
     #[unstable(feature = "shrink_to", reason = "new API", issue = "56431")]
     pub fn shrink_to(&mut self, min_capacity: usize) {
-        self.buf.shrink_to_fit(cmp::max(self.len, min_capacity));
+        if self.capacity() > min_capacity {
+            self.buf.shrink_to_fit(cmp::max(self.len, min_capacity));
+        }
     }
 
     /// Converts the vector into [`Box<[T]>`][owned slice].