Skip to content

Commit 3383204

Browse files
committed
Auto merge of rust-lang#75677 - cuviper:shrink-towel, r=Mark-Simulacrum
Don't panic in Vec::shrink_to_fit We can help the compiler see that `Vec::shrink_to_fit` will never reach the panic case in `RawVec::shrink_to_fit`, just by guarding the call only for cases where the capacity is strictly greater. A capacity less than the length is only possible through an unsafe call to `set_len`, which would break the `Vec` invariants, so `shrink_to_fit` can just ignore that. This removes the panicking code from the examples in both rust-lang#71861 and rust-lang#75636.
2 parents 80c7fb6 + c0991ae commit 3383204

File tree

1 file changed

+4
-1
lines changed

1 file changed

+4
-1
lines changed

alloc/src/vec.rs

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -622,7 +622,10 @@ impl<T> Vec<T> {
622622
/// ```
623623
#[stable(feature = "rust1", since = "1.0.0")]
624624
pub fn shrink_to_fit(&mut self) {
625-
if self.capacity() != self.len {
625+
// The capacity is never less than the length, and there's nothing to do when
626+
// they are equal, so we can avoid the panic case in `RawVec::shrink_to_fit`
627+
// by only calling it with a greater capacity.
628+
if self.capacity() > self.len {
626629
self.buf.shrink_to_fit(self.len);
627630
}
628631
}

0 commit comments

Comments
 (0)