Skip to content

Commit 3f45ec6

Browse files
committed
use nightly waker_getters APIs
Since rust-lang/rust#96992 has stalled, to prevent potential unsoundness caused by transmuting to &WakerHack, we can use nightly waker_getters APIs by gating it behind nightly feature in embassy-executor without waiting for it to be stablized.
1 parent e5495b5 commit 3f45ec6

File tree

2 files changed

+26
-0
lines changed

2 files changed

+26
-0
lines changed

embassy-executor/src/lib.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
#![cfg_attr(not(any(feature = "arch-std", feature = "arch-wasm")), no_std)]
2+
#![cfg_attr(feature = "nightly", feature(waker_getters))]
23
#![allow(clippy::new_without_default)]
34
#![doc = include_str!("../README.md")]
45
#![warn(missing_docs)]

embassy-executor/src/raw/waker.rs

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,7 @@ pub(crate) unsafe fn from_task(p: TaskRef) -> Waker {
3232
/// # Panics
3333
///
3434
/// Panics if the waker is not created by the Embassy executor.
35+
#[cfg(not(feature = "nightly"))]
3536
pub fn task_from_waker(waker: &Waker) -> TaskRef {
3637
// safety: OK because WakerHack has the same layout as Waker.
3738
// This is not really guaranteed because the structs are `repr(Rust)`, it is
@@ -46,7 +47,31 @@ pub fn task_from_waker(waker: &Waker) -> TaskRef {
4647
unsafe { TaskRef::from_ptr(hack.data as *const TaskHeader) }
4748
}
4849

50+
#[cfg(not(feature = "nightly"))]
4951
struct WakerHack {
5052
data: *const (),
5153
vtable: &'static RawWakerVTable,
5254
}
55+
56+
/// Get a task pointer from a waker.
57+
///
58+
/// This can be used as an optimization in wait queues to store task pointers
59+
/// (1 word) instead of full Wakers (2 words). This saves a bit of RAM and helps
60+
/// avoid dynamic dispatch.
61+
///
62+
/// You can use the returned task pointer to wake the task with [`wake_task`](super::wake_task).
63+
///
64+
/// # Panics
65+
///
66+
/// Panics if the waker is not created by the Embassy executor.
67+
#[cfg(feature = "nightly")]
68+
pub fn task_from_waker(waker: &Waker) -> TaskRef {
69+
let raw_waker = waker.as_raw();
70+
71+
if raw_waker.vtable() != &VTABLE {
72+
panic!("Found waker not created by the Embassy executor. `embassy_time::Timer` only works with the Embassy executor.")
73+
}
74+
75+
// safety: our wakers are always created with `TaskRef::as_ptr`
76+
unsafe { TaskRef::from_ptr(raw_waker.data() as *const TaskHeader) }
77+
}

0 commit comments

Comments
 (0)