aboutsummaryrefslogtreecommitdiff
path: root/embassy-executor/src/executor/raw/waker.rs
diff options
context:
space:
mode:
authorDario Nieuwenhuis <[email protected]>2022-07-29 21:58:35 +0200
committerDario Nieuwenhuis <[email protected]>2022-07-29 23:40:36 +0200
commita0f1b0ee01d461607660d2d56b5b1bdc57e0d3fb (patch)
treee60fc8f8db8ec07e55d655c1a830b07f4db0b7d2 /embassy-executor/src/executor/raw/waker.rs
parent8745d646f0976791b7098456aa61adb983fb1c18 (diff)
Split embassy crate into embassy-executor, embassy-util.
Diffstat (limited to 'embassy-executor/src/executor/raw/waker.rs')
-rw-r--r--embassy-executor/src/executor/raw/waker.rs53
1 files changed, 53 insertions, 0 deletions
diff --git a/embassy-executor/src/executor/raw/waker.rs b/embassy-executor/src/executor/raw/waker.rs
new file mode 100644
index 000000000..f6ae332fa
--- /dev/null
+++ b/embassy-executor/src/executor/raw/waker.rs
@@ -0,0 +1,53 @@
1use core::mem;
2use core::ptr::NonNull;
3use core::task::{RawWaker, RawWakerVTable, Waker};
4
5use super::TaskHeader;
6
7const VTABLE: RawWakerVTable = RawWakerVTable::new(clone, wake, wake, drop);
8
9unsafe fn clone(p: *const ()) -> RawWaker {
10 RawWaker::new(p, &VTABLE)
11}
12
13unsafe fn wake(p: *const ()) {
14 (*(p as *mut TaskHeader)).enqueue()
15}
16
17unsafe fn drop(_: *const ()) {
18 // nop
19}
20
21pub(crate) unsafe fn from_task(p: NonNull<TaskHeader>) -> Waker {
22 Waker::from_raw(RawWaker::new(p.as_ptr() as _, &VTABLE))
23}
24
25/// Get a task pointer from a waker.
26///
27/// This can be used as an optimization in wait queues to store task pointers
28/// (1 word) instead of full Wakers (2 words). This saves a bit of RAM and helps
29/// avoid dynamic dispatch.
30///
31/// You can use the returned task pointer to wake the task with [`wake_task`](super::wake_task).
32///
33/// # Panics
34///
35/// Panics if the waker is not created by the Embassy executor.
36pub fn task_from_waker(waker: &Waker) -> NonNull<TaskHeader> {
37 // safety: OK because WakerHack has the same layout as Waker.
38 // This is not really guaranteed because the structs are `repr(Rust)`, it is
39 // indeed the case in the current implementation.
40 // TODO use waker_getters when stable. https://github.com/rust-lang/rust/issues/96992
41 let hack: &WakerHack = unsafe { mem::transmute(waker) };
42 if hack.vtable != &VTABLE {
43 panic!("Found waker not created by the Embassy executor. `embassy_executor::time::Timer` only works with the Embassy executor.")
44 }
45
46 // safety: we never create a waker with a null data pointer.
47 unsafe { NonNull::new_unchecked(hack.data as *mut TaskHeader) }
48}
49
50struct WakerHack {
51 data: *const (),
52 vtable: &'static RawWakerVTable,
53}