Skip to content

Commit c9273f1

Browse files
authored
sync: improve safety comments for WakeList (#6200)
1 parent e05d0f8 commit c9273f1

File tree

1 file changed

+13
-8
lines changed

1 file changed

+13
-8
lines changed

tokio/src/util/wake_list.rs

+13-8
Original file line numberDiff line numberDiff line change
@@ -4,21 +4,22 @@ use std::task::Waker;
44

55
const NUM_WAKERS: usize = 32;
66

7+
/// A list of wakers to be woken.
8+
///
9+
/// # Invariants
10+
///
11+
/// The first `curr` elements of `inner` are initialized.
712
pub(crate) struct WakeList {
813
inner: [MaybeUninit<Waker>; NUM_WAKERS],
914
curr: usize,
1015
}
1116

1217
impl WakeList {
1318
pub(crate) fn new() -> Self {
19+
const UNINIT_WAKER: MaybeUninit<Waker> = MaybeUninit::uninit();
20+
1421
Self {
15-
inner: unsafe {
16-
// safety: Create an uninitialized array of `MaybeUninit`. The
17-
// `assume_init` is safe because the type we are claiming to
18-
// have initialized here is a bunch of `MaybeUninit`s, which do
19-
// not require initialization.
20-
MaybeUninit::uninit().assume_init()
21-
},
22+
inner: [UNINIT_WAKER; NUM_WAKERS],
2223
curr: 0,
2324
}
2425
}
@@ -39,6 +40,8 @@ impl WakeList {
3940
assert!(self.curr <= NUM_WAKERS);
4041
while self.curr > 0 {
4142
self.curr -= 1;
43+
// SAFETY: The first `curr` elements of `WakeList` are initialized, so by decrementing
44+
// `curr`, we can take ownership of the last item.
4245
let waker = unsafe { ptr::read(self.inner[self.curr].as_mut_ptr()) };
4346
waker.wake();
4447
}
@@ -47,7 +50,9 @@ impl WakeList {
4750

4851
impl Drop for WakeList {
4952
fn drop(&mut self) {
50-
let slice = ptr::slice_from_raw_parts_mut(self.inner.as_mut_ptr() as *mut Waker, self.curr);
53+
let slice =
54+
ptr::slice_from_raw_parts_mut(self.inner.as_mut_ptr().cast::<Waker>(), self.curr);
55+
// SAFETY: The first `curr` elements are initialized, so we can drop them.
5156
unsafe { ptr::drop_in_place(slice) };
5257
}
5358
}

0 commit comments

Comments
 (0)