Skip to content

Commit

Permalink
Check whether vector value needs to be dropped in Vec#truncate
Browse files Browse the repository at this point in the history
Fixes #17633.
  • Loading branch information
KamilaBorowska committed Jan 28, 2019
1 parent 7187db6 commit 39ee117
Showing 1 changed file with 16 additions and 13 deletions.
29 changes: 16 additions & 13 deletions src/liballoc/vec.rs
Original file line number Diff line number Diff line change
Expand Up @@ -687,20 +687,23 @@ impl<T> Vec<T> {
#[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);

// drop any extra elements
for _ in len..current_len {
local_len.decrement_len(1);
ptr = ptr.offset(-1);
ptr::drop_in_place(ptr);
if mem::needs_drop::<T>() {
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);
}
}
} else if current_len > len {
self.len = len;
}
}

Expand Down

0 comments on commit 39ee117

Please sign in to comment.