Skip to content

Commit 4adebb9

Browse files
authored
Rollup merge of #71148 - bluss:vec-drop-raw-slice, r=RalfJung
Vec drop and truncate: drop using raw slice *mut [T] By creating a *mut [T] directly (without going through &mut [T]), avoid questions of validity of the contents of the slice. Consider the following risky code: ```rust unsafe { let mut v = Vec::<bool>::with_capacity(16); v.set_len(16); } ``` The intention is that with this change, we avoid one of the soundness questions about the above snippet, because Vec::drop no longer produces a mutable slice of the vector's contents. r? @RalfJung
2 parents 7ced01a + f654daf commit 4adebb9

File tree

1 file changed

+10
-4
lines changed

1 file changed

+10
-4
lines changed

src/liballoc/vec.rs

+10-4
Original file line numberDiff line numberDiff line change
@@ -741,7 +741,7 @@ impl<T> Vec<T> {
741741
return;
742742
}
743743
let remaining_len = self.len - len;
744-
let s = slice::from_raw_parts_mut(self.as_mut_ptr().add(len), remaining_len);
744+
let s = ptr::slice_from_raw_parts_mut(self.as_mut_ptr().add(len), remaining_len);
745745
self.len = len;
746746
ptr::drop_in_place(s);
747747
}
@@ -2379,7 +2379,9 @@ unsafe impl<#[may_dangle] T> Drop for Vec<T> {
23792379
fn drop(&mut self) {
23802380
unsafe {
23812381
// use drop for [T]
2382-
ptr::drop_in_place(&mut self[..]);
2382+
// use a raw slice to refer to the elements of the vector as weakest necessary type;
2383+
// could avoid questions of validity in certain cases
2384+
ptr::drop_in_place(ptr::slice_from_raw_parts_mut(self.as_mut_ptr(), self.len))
23832385
}
23842386
// RawVec handles deallocation
23852387
}
@@ -2596,7 +2598,11 @@ impl<T> IntoIter<T> {
25962598
/// ```
25972599
#[stable(feature = "vec_into_iter_as_slice", since = "1.15.0")]
25982600
pub fn as_mut_slice(&mut self) -> &mut [T] {
2599-
unsafe { slice::from_raw_parts_mut(self.ptr as *mut T, self.len()) }
2601+
unsafe { &mut *self.as_raw_mut_slice() }
2602+
}
2603+
2604+
fn as_raw_mut_slice(&mut self) -> *mut [T] {
2605+
ptr::slice_from_raw_parts_mut(self.ptr as *mut T, self.len())
26002606
}
26012607
}
26022608

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

0 commit comments

Comments
 (0)