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