Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
44 changes: 44 additions & 0 deletions library/core/src/task/wake.rs
Original file line number Diff line number Diff line change
Expand Up @@ -584,6 +584,28 @@ impl Waker {
pub fn vtable(&self) -> &'static RawWakerVTable {
self.waker.vtable
}

/// Constructs a `Waker` from a function pointer.
#[inline]
#[must_use]
#[unstable(feature = "waker_from_fn_ptr", issue = "146055")]
pub const fn from_fn_ptr(f: fn()) -> Self {
// SAFETY: Unsafe is used for transmutes, pointer came from `fn()` so it
// is sound to transmute it back to `fn()`.
static VTABLE: RawWakerVTable = unsafe {
RawWakerVTable::new(
|this| RawWaker::new(this, &VTABLE),
|this| transmute::<*const (), fn()>(this)(),
|this| transmute::<*const (), fn()>(this)(),
|_| {},
)
};
let raw = RawWaker::new(f as *const (), &VTABLE);

// SAFETY: `clone` is just a copy, `drop` is a no-op while `wake` and
// `wake_by_ref` just call the function pointer.
unsafe { Self::from_raw(raw) }
}
}

#[stable(feature = "futures_api", since = "1.36.0")]
Expand Down Expand Up @@ -879,6 +901,28 @@ impl LocalWaker {
pub fn vtable(&self) -> &'static RawWakerVTable {
self.waker.vtable
}

/// Constructs a `LocalWaker` from a function pointer.
#[inline]
#[must_use]
#[unstable(feature = "waker_from_fn_ptr", issue = "146055")]
pub const fn from_fn_ptr(f: fn()) -> Self {
// SAFETY: Unsafe is used for transmutes, pointer came from `fn()` so it
// is sound to transmute it back to `fn()`.
static VTABLE: RawWakerVTable = unsafe {
RawWakerVTable::new(
|this| RawWaker::new(this, &VTABLE),
|this| transmute::<*const (), fn()>(this)(),
|this| transmute::<*const (), fn()>(this)(),
|_| {},
)
};
let raw = RawWaker::new(f as *const (), &VTABLE);

// SAFETY: `clone` is just a copy, `drop` is a no-op while `wake` and
// `wake_by_ref` just call the function pointer.
unsafe { Self::from_raw(raw) }
}
}
#[unstable(feature = "local_waker", issue = "118959")]
impl Clone for LocalWaker {
Expand Down
Loading