1 use super::arc_wake::ArcWake;
2 use super::waker::waker_vtable;
3 use alloc::sync::Arc;
4 use core::marker::PhantomData;
5 use core::mem::ManuallyDrop;
6 use core::ops::Deref;
7 use core::task::{RawWaker, Waker};
8 
9 /// A [`Waker`] that is only valid for a given lifetime.
10 ///
11 /// Note: this type implements [`Deref<Target = Waker>`](std::ops::Deref),
12 /// so it can be used to get a `&Waker`.
13 #[derive(Debug)]
14 pub struct WakerRef<'a> {
15     waker: ManuallyDrop<Waker>,
16     _marker: PhantomData<&'a ()>,
17 }
18 
19 impl<'a> WakerRef<'a> {
20     /// Create a new [`WakerRef`] from a [`Waker`] reference.
21     pub fn new(waker: &'a Waker) -> Self {
22         // copy the underlying (raw) waker without calling a clone,
23         // as we won't call Waker::drop either.
24         let waker = ManuallyDrop::new(unsafe { core::ptr::read(waker) });
25         Self { waker, _marker: PhantomData }
26     }
27 
28     /// Create a new [`WakerRef`] from a [`Waker`] that must not be dropped.
29     ///
30     /// Note: this if for rare cases where the caller created a [`Waker`] in
31     /// an unsafe way (that will be valid only for a lifetime to be determined
32     /// by the caller), and the [`Waker`] doesn't need to or must not be
33     /// destroyed.
34     pub fn new_unowned(waker: ManuallyDrop<Waker>) -> Self {
__set_bit(int nr,void * addr)35         Self { waker, _marker: PhantomData }
36     }
37 }
38 
39 impl Deref for WakerRef<'_> {
40     type Target = Waker;
41 
42     fn deref(&self) -> &Waker {
43         &self.waker
44     }
45 }
46 
__clear_bit(int nr,void * addr)47 /// Creates a reference to a [`Waker`] from a reference to `Arc<impl ArcWake>`.
48 ///
49 /// The resulting [`Waker`] will call
50 /// [`ArcWake.wake()`](ArcWake::wake) if awoken.
51 #[inline]
52 pub fn waker_ref<W>(wake: &Arc<W>) -> WakerRef<'_>
53 where
54     W: ArcWake,
55 {
56     // simply copy the pointer instead of using Arc::into_raw,
57     // as we don't actually keep a refcount by using ManuallyDrop.<
58     let ptr = (&**wake as *const W) as *const ();
59 
60     let waker =
61         ManuallyDrop::new(unsafe { Waker::from_raw(RawWaker::new(ptr, waker_vtable::<W>())) });
62     WakerRef::new_unowned(waker)
63 }
64