Skip to main content

embassy_executor/raw/
waker.rs

1use core::task::{RawWaker, RawWakerVTable, Waker};
2
3use super::{TaskHeader, TaskRef, wake_task};
4
5static VTABLE: RawWakerVTable = RawWakerVTable::new(clone, wake, wake, drop);
6
7unsafe fn clone(p: *const ()) -> RawWaker {
8    RawWaker::new(p, &VTABLE)
9}
10
11unsafe fn wake(p: *const ()) {
12    wake_task(TaskRef::from_ptr(p as *const TaskHeader))
13}
14
15unsafe fn drop(_: *const ()) {
16    // nop
17}
18
19pub(crate) unsafe fn from_task(p: TaskRef) -> Waker {
20    Waker::from_raw(RawWaker::new(p.as_ptr() as _, &VTABLE))
21}
22
23/// Get a task pointer from a waker.
24///
25/// This can be used as an optimization in wait queues to store task pointers
26/// (1 word) instead of full Wakers (2 words). This saves a bit of RAM and helps
27/// avoid dynamic dispatch.
28///
29/// You can use the returned task pointer to wake the task with [`wake_task`].
30///
31/// # Panics
32///
33/// Panics if the waker is not created by the Embassy executor.
34pub fn task_from_waker(waker: &Waker) -> TaskRef {
35    unwrap!(
36        try_task_from_waker(waker),
37        "Found waker not created by the Embassy executor. Unless the generic timer queue is enabled, `embassy_time::Timer` only works with the Embassy executor."
38    )
39}
40
41pub(crate) fn try_task_from_waker(waker: &Waker) -> Option<TaskRef> {
42    // make sure to compare vtable addresses. Doing `==` on the references
43    // will compare the contents, which is slower.
44    if waker.vtable() as *const _ != &VTABLE as *const _ {
45        return None;
46    }
47    // safety: our wakers are always created with `TaskRef::as_ptr`
48    Some(unsafe { TaskRef::from_ptr(waker.data() as *const TaskHeader) })
49}