1//! Utilities for creating zero-cost wakers that don't do anything.
2
3use core::ptr::null;
4use core::task::{RawWaker, RawWakerVTable, Waker};
5
6unsafe fn noop_clone(_data: *const ()) -> RawWaker {
7 noop_raw_waker()
8}
9
10unsafe fn noop(_data: *const ()) {}
11
12const NOOP_WAKER_VTABLE: RawWakerVTable = RawWakerVTable::new(noop_clone, noop, noop, noop);
13
14const fn noop_raw_waker() -> RawWaker {
15 RawWaker::new(null(), &NOOP_WAKER_VTABLE)
16}
17
18/// Create a new [`Waker`] which does
19/// nothing when `wake()` is called on it.
20///
21/// # Examples
22///
23/// ```
24/// use futures::task::noop_waker;
25/// let waker = noop_waker();
26/// waker.wake();
27/// ```
28#[inline]
29pub fn noop_waker() -> Waker {
30 // FIXME: Since 1.46.0 we can use transmute in consts, allowing this function to be const.
31 unsafe { Waker::from_raw(noop_raw_waker()) }
32}
33
34/// Get a static reference to a [`Waker`] which
35/// does nothing when `wake()` is called on it.
36///
37/// # Examples
38///
39/// ```
40/// use futures::task::noop_waker_ref;
41/// let waker = noop_waker_ref();
42/// waker.wake_by_ref();
43/// ```
44#[inline]
45pub fn noop_waker_ref() -> &'static Waker {
46 struct SyncRawWaker(RawWaker);
47 unsafe impl Sync for SyncRawWaker {}
48
49 static NOOP_WAKER_INSTANCE: SyncRawWaker = SyncRawWaker(noop_raw_waker());
50
51 // SAFETY: `Waker` is #[repr(transparent)] over its `RawWaker`.
52 unsafe { &*(&NOOP_WAKER_INSTANCE.0 as *const RawWaker as *const Waker) }
53}
54
55#[cfg(test)]
56mod tests {
57 #[test]
58 #[cfg(feature = "std")]
59 fn issue_2091_cross_thread_segfault() {
60 let waker = std::thread::spawn(super::noop_waker_ref).join().unwrap();
61 waker.wake_by_ref();
62 }
63}
64