Skip to content

Use drop_in_place in Vec and VecDeque #32012

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Mar 3, 2016
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 7 additions & 11 deletions src/libcollections/vec.rs
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ use borrow::ToOwned;
use core::cmp::Ordering;
use core::fmt;
use core::hash::{self, Hash};
use core::intrinsics::{arith_offset, assume, needs_drop};
use core::intrinsics::{arith_offset, assume};
use core::iter::FromIterator;
use core::mem;
use core::ops::{Index, IndexMut};
Expand Down Expand Up @@ -497,10 +497,11 @@ impl<T> Vec<T> {
unsafe {
// drop any extra elements
while len < self.len {
// decrement len before the read(), so a panic on Drop doesn't
// re-drop the just-failed value.
// decrement len before the drop_in_place(), so a panic on Drop
// doesn't re-drop the just-failed value.
self.len -= 1;
ptr::read(self.get_unchecked(self.len));
let len = self.len;
ptr::drop_in_place(self.get_unchecked_mut(len));
}
}
}
Expand Down Expand Up @@ -1471,13 +1472,8 @@ impl<T> Drop for Vec<T> {
fn drop(&mut self) {
if self.buf.unsafe_no_drop_flag_needs_drop() {
unsafe {
// The branch on needs_drop() is an -O1 performance optimization.
// Without the branch, dropping Vec<u8> takes linear time.
if needs_drop::<T>() {
for x in self.iter_mut() {
ptr::drop_in_place(x);
}
}
// use drop for [T]
ptr::drop_in_place(&mut self[..]);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Whoa I had no idea this was possible, nifty!

}
}
// RawVec handles deallocation
Expand Down
7 changes: 6 additions & 1 deletion src/libcollections/vec_deque.rs
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,12 @@ impl<T: Clone> Clone for VecDeque<T> {
impl<T> Drop for VecDeque<T> {
#[unsafe_destructor_blind_to_params]
fn drop(&mut self) {
self.clear();
let (front, back) = self.as_mut_slices();
unsafe {
// use drop for [T]
ptr::drop_in_place(front);
ptr::drop_in_place(back);
}
// RawVec handles deallocation
}
}
Expand Down