Skip to content

Commit

Permalink
Rollup merge of rust-lang#64375 - kornelski:vecdrop, r=rkruppe
Browse files Browse the repository at this point in the history
Fast path for vec.clear/truncate

For trivial types like `u8`, `vec.truncate()`/`vec.clear()` relies on the optimizer to remove the loop. This means more work in debug builds, and more work for the optimizer.

Avoiding this busywork is exactly what `mem::needs_drop::<T>()` is for.
  • Loading branch information
Centril committed Sep 13, 2019
2 parents 8b3beb5 + 223600a commit b058147
Showing 1 changed file with 17 additions and 13 deletions.
30 changes: 17 additions & 13 deletions src/liballoc/vec.rs
Original file line number Diff line number Diff line change
Expand Up @@ -685,21 +685,25 @@ impl<T> Vec<T> {
/// [`drain`]: #method.drain
#[stable(feature = "rust1", since = "1.0.0")]
pub fn truncate(&mut self, len: usize) {
let current_len = self.len;
unsafe {
let mut ptr = self.as_mut_ptr().add(self.len);
// Set the final length at the end, keeping in mind that
// dropping an element might panic. Works around a missed
// optimization, as seen in the following issue:
// https://github.com/rust-lang/rust/issues/51802
let mut local_len = SetLenOnDrop::new(&mut self.len);
if mem::needs_drop::<T>() {
let current_len = self.len;
unsafe {
let mut ptr = self.as_mut_ptr().add(self.len);
// Set the final length at the end, keeping in mind that
// dropping an element might panic. Works around a missed
// optimization, as seen in the following issue:
// https://github.com/rust-lang/rust/issues/51802
let mut local_len = SetLenOnDrop::new(&mut self.len);

// drop any extra elements
for _ in len..current_len {
local_len.decrement_len(1);
ptr = ptr.offset(-1);
ptr::drop_in_place(ptr);
// drop any extra elements
for _ in len..current_len {
local_len.decrement_len(1);
ptr = ptr.offset(-1);
ptr::drop_in_place(ptr);
}
}
} else if len <= self.len {
self.len = len;
}
}

Expand Down

0 comments on commit b058147

Please sign in to comment.