Skip to content

Commit 71d857a

Browse files
Document uses of unsafe in VecDrop
1 parent 2408e71 commit 71d857a

File tree

1 file changed

+9
-5
lines changed

1 file changed

+9
-5
lines changed

src/vec.rs

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,10 @@ use core::{
99

1010
/// Workaround forbidden specialization of Drop
1111
pub trait VecDrop {
12+
// SAFETY: drop_with_len will be called to call drop in place the first `len` elements of the buffer.
13+
// Only the Owned buffer (`[MaybeUninit<T>; N]`) must drop the items
14+
// and the view (`[MaybeUninit<T>]`) drops nothing.
15+
// `drop_with_len `assumes that the buffer can contain `len` elements.
1216
unsafe fn drop_with_len(&mut self, len: usize);
1317
}
1418

@@ -21,12 +25,11 @@ impl<T> VecDrop for [MaybeUninit<T>] {
2125
impl<T, const N: usize> VecDrop for [MaybeUninit<T>; N] {
2226
unsafe fn drop_with_len(&mut self, len: usize) {
2327
// NOTE(unsafe) avoid bound checks in the slicing operation
24-
// &mut buffer[..self.len]
25-
let mut_slice = unsafe { slice::from_raw_parts_mut(self.as_mut_ptr() as *mut T, len) };
28+
// &mut buffer[..len]
29+
// SAFETY: buffer[..len] must be valid to drop given the safety requirement of the trait definition.
30+
let mut_slice = slice::from_raw_parts_mut(self.as_mut_ptr() as *mut T, len);
2631
// We drop each element used in the vector by turning into a `&mut [T]`.
27-
unsafe {
28-
ptr::drop_in_place(mut_slice);
29-
}
32+
ptr::drop_in_place(mut_slice);
3033
}
3134
}
3235

@@ -1540,6 +1543,7 @@ impl<T, const N: usize, const M: usize> From<[T; M]> for Vec<T, N> {
15401543

15411544
impl<T: ?Sized + VecDrop> Drop for VecInner<T> {
15421545
fn drop(&mut self) {
1546+
// SAFETY: the buffer contains initialized data for the range 0..self.len
15431547
unsafe { self.buffer.drop_with_len(self.len) }
15441548
}
15451549
}

0 commit comments

Comments
 (0)