Skip to content

[FEATURE REQUEST] Waker::from_fn_ptr #146055

@Ddystopia

Description

@Ddystopia

Hello, it would be a very easy and small change to add from_fn_ptr to Waker - it doesn't need need any reference counting, safe, simple, efficient. Something as simple as that:

    #[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) }
    }

Prior Art

Crates like https://docs.rs/waker-fn/latest/waker_fn/ are overly generic and have additional overhead, Arc in this case.

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-async-awaitArea: Async & AwaitC-feature-requestCategory: A feature request, i.e: not implemented / a PR.T-libsRelevant to the library team, which will review and decide on the PR/issue.T-libs-apiRelevant to the library API team, which will review and decide on the PR/issue.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions