Merge pull request #3069 from zjp-CN/waker-getters

minimize cfg code in task_from_waker
This commit is contained in:
Dario Nieuwenhuis 2024-06-13 00:17:26 +00:00 committed by GitHub
commit 8d79679bb2
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194

View File

@ -32,35 +32,32 @@ pub(crate) unsafe fn from_task(p: TaskRef) -> Waker {
/// ///
/// Panics if the waker is not created by the Embassy executor. /// Panics if the waker is not created by the Embassy executor.
pub fn task_from_waker(waker: &Waker) -> TaskRef { pub fn task_from_waker(waker: &Waker) -> TaskRef {
#[cfg(not(feature = "nightly"))] let (vtable, data) = {
{ #[cfg(not(feature = "nightly"))]
struct WakerHack { {
data: *const (), struct WakerHack {
vtable: &'static RawWakerVTable, data: *const (),
vtable: &'static RawWakerVTable,
}
// 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 { core::mem::transmute(waker) };
(hack.vtable, hack.data)
} }
// safety: OK because WakerHack has the same layout as Waker. #[cfg(feature = "nightly")]
// This is not really guaranteed because the structs are `repr(Rust)`, it is {
// indeed the case in the current implementation. let raw_waker = waker.as_raw();
// TODO use waker_getters when stable. https://github.com/rust-lang/rust/issues/96992 (raw_waker.vtable(), raw_waker.data())
let hack: &WakerHack = unsafe { core::mem::transmute(waker) };
if hack.vtable != &VTABLE {
panic!("Found waker not created by the Embassy executor. `embassy_time::Timer` only works with the Embassy executor.")
} }
};
// safety: our wakers are always created with `TaskRef::as_ptr` if vtable != &VTABLE {
unsafe { TaskRef::from_ptr(hack.data as *const TaskHeader) } panic!("Found waker not created by the Embassy executor. `embassy_time::Timer` only works with the Embassy executor.")
}
#[cfg(feature = "nightly")]
{
let raw_waker = waker.as_raw();
if raw_waker.vtable() != &VTABLE {
panic!("Found waker not created by the Embassy executor. `embassy_time::Timer` only works with the Embassy executor.")
}
// safety: our wakers are always created with `TaskRef::as_ptr`
unsafe { TaskRef::from_ptr(raw_waker.data() as *const TaskHeader) }
} }
// safety: our wakers are always created with `TaskRef::as_ptr`
unsafe { TaskRef::from_ptr(data as *const TaskHeader) }
} }