1//! Convert closures into wakers.
2//!
3//! A [`Waker`] is just a fancy callback. This crate converts regular closures into wakers.
4
5#![no_std]
6#![forbid(unsafe_code)]
7#![warn(missing_docs, missing_debug_implementations, rust_2018_idioms)]
8#![doc(
9 html_favicon_url = "https://raw.githubusercontent.com/smol-rs/smol/master/assets/images/logo_fullsize_transparent.png"
10)]
11#![doc(
12 html_logo_url = "https://raw.githubusercontent.com/smol-rs/smol/master/assets/images/logo_fullsize_transparent.png"
13)]
14
15extern crate alloc;
16
17use alloc::sync::Arc;
18use alloc::task::Wake;
19use core::task::Waker;
20
21/// Converts a closure into a [`Waker`].
22///
23/// The closure gets called every time the waker is woken.
24///
25/// # Examples
26///
27/// ```
28/// use waker_fn::waker_fn;
29///
30/// let waker = waker_fn(|| println!("woken"));
31///
32/// waker.wake_by_ref(); // Prints "woken".
33/// waker.wake(); // Prints "woken".
34/// ```
35pub fn waker_fn<F: Fn() + Send + Sync + 'static>(f: F) -> Waker {
36 Waker::from(Arc::new(data:Helper(f)))
37}
38
39struct Helper<F>(F);
40
41impl<F: Fn() + Send + Sync + 'static> Wake for Helper<F> {
42 fn wake(self: Arc<Self>) {
43 (self.0)();
44 }
45
46 fn wake_by_ref(self: &Arc<Self>) {
47 (self.0)();
48 }
49}
50