2020-12-26 23:44:53 +01:00
|
|
|
use core::mem;
|
2021-02-02 05:14:52 +01:00
|
|
|
use core::ptr::NonNull;
|
2020-12-26 17:22:36 +01:00
|
|
|
use core::task::{RawWaker, RawWakerVTable, Waker};
|
|
|
|
|
2022-08-01 12:26:37 +02:00
|
|
|
use super::{wake_task, TaskHeader};
|
2020-12-26 17:22:36 +01:00
|
|
|
|
2020-12-26 23:44:53 +01:00
|
|
|
const VTABLE: RawWakerVTable = RawWakerVTable::new(clone, wake, wake, drop);
|
2020-12-26 17:22:36 +01:00
|
|
|
|
|
|
|
unsafe fn clone(p: *const ()) -> RawWaker {
|
|
|
|
RawWaker::new(p, &VTABLE)
|
|
|
|
}
|
|
|
|
|
|
|
|
unsafe fn wake(p: *const ()) {
|
2022-08-01 12:26:37 +02:00
|
|
|
wake_task(NonNull::new_unchecked(p as *mut TaskHeader))
|
2020-12-26 17:22:36 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
unsafe fn drop(_: *const ()) {
|
|
|
|
// nop
|
|
|
|
}
|
|
|
|
|
2021-03-18 00:20:02 +01:00
|
|
|
pub(crate) unsafe fn from_task(p: NonNull<TaskHeader>) -> Waker {
|
2021-02-02 05:14:52 +01:00
|
|
|
Waker::from_raw(RawWaker::new(p.as_ptr() as _, &VTABLE))
|
2020-12-26 17:22:36 +01:00
|
|
|
}
|
2020-12-26 23:44:53 +01:00
|
|
|
|
2021-08-26 00:20:52 +02:00
|
|
|
/// Get a task pointer from a waker.
|
|
|
|
///
|
2022-05-01 19:25:45 +02:00
|
|
|
/// This can be used as an optimization in wait queues to store task pointers
|
2021-08-26 00:20:52 +02:00
|
|
|
/// (1 word) instead of full Wakers (2 words). This saves a bit of RAM and helps
|
|
|
|
/// avoid dynamic dispatch.
|
|
|
|
///
|
|
|
|
/// You can use the returned task pointer to wake the task with [`wake_task`](super::wake_task).
|
|
|
|
///
|
|
|
|
/// # Panics
|
|
|
|
///
|
|
|
|
/// Panics if the waker is not created by the Embassy executor.
|
2022-06-26 00:13:31 +02:00
|
|
|
pub fn task_from_waker(waker: &Waker) -> NonNull<TaskHeader> {
|
|
|
|
// safety: OK because WakerHack has the same layout as Waker.
|
|
|
|
// This is not really guaranteed because the structs are `repr(Rust)`, it is
|
|
|
|
// indeed the case in the current implementation.
|
|
|
|
// TODO use waker_getters when stable. https://github.com/rust-lang/rust/issues/96992
|
|
|
|
let hack: &WakerHack = unsafe { mem::transmute(waker) };
|
2021-06-07 00:10:54 +02:00
|
|
|
if hack.vtable != &VTABLE {
|
2022-08-17 23:40:16 +02:00
|
|
|
panic!("Found waker not created by the Embassy executor. `embassy_time::Timer` only works with the Embassy executor.")
|
2021-06-07 00:10:54 +02:00
|
|
|
}
|
2022-06-26 00:13:31 +02:00
|
|
|
|
|
|
|
// safety: we never create a waker with a null data pointer.
|
|
|
|
unsafe { NonNull::new_unchecked(hack.data as *mut TaskHeader) }
|
2020-12-26 23:44:53 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
struct WakerHack {
|
|
|
|
data: *const (),
|
|
|
|
vtable: &'static RawWakerVTable,
|
|
|
|
}
|