use std::mem::drop;
use std::mem::ManuallyDrop;
use std::sync::Weak;
use std::task::RawWaker;
use std::task::RawWakerVTable;
use std::task::Waker;
#[derive(Debug, Hash, PartialEq, Eq, Copy, Clone)]
pub(crate) struct WakerToken(pub(crate) usize);
pub(crate) trait WeakWake: Send + Sync {
fn wake_by_ref(weak_self: &Weak<Self>);
fn wake(weak_self: Weak<Self>) {
Self::wake_by_ref(&weak_self)
}
}
fn waker_vtable<W: WeakWake>() -> &'static RawWakerVTable {
&RawWakerVTable::new(
clone_weak_raw::<W>,
wake_weak_raw::<W>,
wake_by_ref_weak_raw::<W>,
drop_weak_raw::<W>,
)
}
unsafe fn clone_weak_raw<W: WeakWake>(data: *const ()) -> RawWaker {
let weak = ManuallyDrop::new(Weak::<W>::from_raw(data as *const W));
let _weak_clone: ManuallyDrop<_> = weak.clone();
RawWaker::new(data, waker_vtable::<W>())
}
unsafe fn wake_weak_raw<W: WeakWake>(data: *const ()) {
let weak: Weak<W> = Weak::from_raw(data as *const W);
WeakWake::wake(weak)
}
unsafe fn wake_by_ref_weak_raw<W: WeakWake>(data: *const ()) {
let weak = ManuallyDrop::new(Weak::<W>::from_raw(data as *const W));
WeakWake::wake_by_ref(&weak)
}
unsafe fn drop_weak_raw<W: WeakWake>(data: *const ()) {
drop(Weak::from_raw(data as *const W))
}
pub(crate) fn new_waker<W: WeakWake>(w: Weak<W>) -> Waker {
#[allow(clippy::undocumented_unsafe_blocks)]
unsafe {
Waker::from_raw(RawWaker::new(
w.into_raw() as *const (),
waker_vtable::<W>(),
))
}
}