Skip to content

Commit 39ee117

Browse files
Check whether vector value needs to be dropped in Vec#truncate
Fixes #17633.
1 parent 7187db6 commit 39ee117

File tree

1 file changed

+16
-13
lines changed

1 file changed

+16
-13
lines changed

src/liballoc/vec.rs

+16-13
Original file line numberDiff line numberDiff line change
@@ -687,20 +687,23 @@ impl<T> Vec<T> {
687687
#[stable(feature = "rust1", since = "1.0.0")]
688688
pub fn truncate(&mut self, len: usize) {
689689
let current_len = self.len;
690-
unsafe {
691-
let mut ptr = self.as_mut_ptr().add(self.len);
692-
// Set the final length at the end, keeping in mind that
693-
// dropping an element might panic. Works around a missed
694-
// optimization, as seen in the following issue:
695-
// https://github.com/rust-lang/rust/issues/51802
696-
let mut local_len = SetLenOnDrop::new(&mut self.len);
697-
698-
// drop any extra elements
699-
for _ in len..current_len {
700-
local_len.decrement_len(1);
701-
ptr = ptr.offset(-1);
702-
ptr::drop_in_place(ptr);
690+
if mem::needs_drop::<T>() {
691+
unsafe {
692+
let mut ptr = self.as_mut_ptr().add(self.len);
693+
// Set the final length at the end, keeping in mind that
694+
// dropping an element might panic. Works around a missed
695+
// optimization, as seen in the following issue:
696+
// https://github.com/rust-lang/rust/issues/51802
697+
let mut local_len = SetLenOnDrop::new(&mut self.len);
698+
// drop any extra elements
699+
for _ in len..current_len {
700+
local_len.decrement_len(1);
701+
ptr = ptr.offset(-1);
702+
ptr::drop_in_place(ptr);
703+
}
703704
}
705+
} else if current_len > len {
706+
self.len = len;
704707
}
705708
}
706709

0 commit comments

Comments
 (0)