Skip to content

Commit

Permalink
Vec IntoIter: Drop using raw slice
Browse files Browse the repository at this point in the history
Update Vec drop with a comment to explain why we want to use a raw
slice, and extend this pattern to also include the Vec's IntoIter.
  • Loading branch information
bluss committed Apr 28, 2020
1 parent 7612ad7 commit f654daf
Showing 1 changed file with 8 additions and 2 deletions.
10 changes: 8 additions & 2 deletions src/liballoc/vec.rs
Expand Up @@ -2379,6 +2379,8 @@ unsafe impl<#[may_dangle] T> Drop for Vec<T> {
fn drop(&mut self) {
unsafe {
// use drop for [T]
// use a raw slice to refer to the elements of the vector as weakest necessary type;
// could avoid questions of validity in certain cases
ptr::drop_in_place(ptr::slice_from_raw_parts_mut(self.as_mut_ptr(), self.len))
}
// RawVec handles deallocation
Expand Down Expand Up @@ -2596,7 +2598,11 @@ impl<T> IntoIter<T> {
/// ```
#[stable(feature = "vec_into_iter_as_slice", since = "1.15.0")]
pub fn as_mut_slice(&mut self) -> &mut [T] {
unsafe { slice::from_raw_parts_mut(self.ptr as *mut T, self.len()) }
unsafe { &mut *self.as_raw_mut_slice() }
}

fn as_raw_mut_slice(&mut self) -> *mut [T] {
ptr::slice_from_raw_parts_mut(self.ptr as *mut T, self.len())
}
}

Expand Down Expand Up @@ -2708,7 +2714,7 @@ unsafe impl<#[may_dangle] T> Drop for IntoIter<T> {
let guard = DropGuard(self);
// destroy the remaining elements
unsafe {
ptr::drop_in_place(guard.0.as_mut_slice());
ptr::drop_in_place(guard.0.as_raw_mut_slice());
}
// now `guard` will be dropped and do the rest
}
Expand Down

0 comments on commit f654daf

Please sign in to comment.