Split lists of `Waker` and directly-registered `Future` callbacks
[rust-lightning] / lightning / src / util / wakers.rs
1 // This file is Copyright its original authors, visible in version control
2 // history.
3 //
4 // This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
5 // or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
7 // You may not use this file except in accordance with one or both of these
8 // licenses.
9
10 //! Utilities which allow users to block on some future notification from LDK. These are
11 //! specifically used by [`ChannelManager`] to allow waiting until the [`ChannelManager`] needs to
12 //! be re-persisted.
13 //!
14 //! [`ChannelManager`]: crate::ln::channelmanager::ChannelManager
15
16 use alloc::sync::Arc;
17 use core::mem;
18 use crate::sync::Mutex;
19
20 use crate::prelude::*;
21
22 #[cfg(feature = "std")]
23 use crate::sync::Condvar;
24 #[cfg(feature = "std")]
25 use std::time::Duration;
26
27 use core::future::Future as StdFuture;
28 use core::task::{Context, Poll};
29 use core::pin::Pin;
30
31
32 /// Used to signal to one of many waiters that the condition they're waiting on has happened.
33 pub(crate) struct Notifier {
34         notify_pending: Mutex<(bool, Option<Arc<Mutex<FutureState>>>)>,
35 }
36
37 impl Notifier {
38         pub(crate) fn new() -> Self {
39                 Self {
40                         notify_pending: Mutex::new((false, None)),
41                 }
42         }
43
44         /// Wake waiters, tracking that wake needs to occur even if there are currently no waiters.
45         pub(crate) fn notify(&self) {
46                 let mut lock = self.notify_pending.lock().unwrap();
47                 if let Some(future_state) = &lock.1 {
48                         if complete_future(future_state) {
49                                 lock.1 = None;
50                                 return;
51                         }
52                 }
53                 lock.0 = true;
54         }
55
56         /// Gets a [`Future`] that will get woken up with any waiters
57         pub(crate) fn get_future(&self) -> Future {
58                 let mut lock = self.notify_pending.lock().unwrap();
59                 if let Some(existing_state) = &lock.1 {
60                         if existing_state.lock().unwrap().callbacks_made {
61                                 // If the existing `FutureState` has completed and actually made callbacks,
62                                 // consider the notification flag to have been cleared and reset the future state.
63                                 lock.1.take();
64                                 lock.0 = false;
65                         }
66                 }
67                 if let Some(existing_state) = &lock.1 {
68                         Future { state: Arc::clone(&existing_state) }
69                 } else {
70                         let state = Arc::new(Mutex::new(FutureState {
71                                 callbacks: Vec::new(),
72                                 std_future_callbacks: Vec::new(),
73                                 callbacks_with_state: Vec::new(),
74                                 complete: lock.0,
75                                 callbacks_made: false,
76                         }));
77                         lock.1 = Some(Arc::clone(&state));
78                         Future { state }
79                 }
80         }
81
82         #[cfg(any(test, feature = "_test_utils"))]
83         pub fn notify_pending(&self) -> bool {
84                 self.notify_pending.lock().unwrap().0
85         }
86 }
87
88 macro_rules! define_callback { ($($bounds: path),*) => {
89 /// A callback which is called when a [`Future`] completes.
90 ///
91 /// Note that this MUST NOT call back into LDK directly, it must instead schedule actions to be
92 /// taken later. Rust users should use the [`std::future::Future`] implementation for [`Future`]
93 /// instead.
94 ///
95 /// Note that the [`std::future::Future`] implementation may only work for runtimes which schedule
96 /// futures when they receive a wake, rather than immediately executing them.
97 pub trait FutureCallback : $($bounds +)* {
98         /// The method which is called.
99         fn call(&self);
100 }
101
102 impl<F: Fn() $(+ $bounds)*> FutureCallback for F {
103         fn call(&self) { (self)(); }
104 }
105 } }
106
107 #[cfg(feature = "std")]
108 define_callback!(Send);
109 #[cfg(not(feature = "std"))]
110 define_callback!();
111
112 pub(crate) struct FutureState {
113         // `callbacks` count as having woken the users' code (as they go direct to the user), but
114         // `std_future_callbacks` and `callbacks_with_state` do not (as the first just wakes a future,
115         // we only count it after another `poll()` and the second wakes a `Sleeper` which handles
116         // setting `callbacks_made` itself).
117         callbacks: Vec<Box<dyn FutureCallback>>,
118         std_future_callbacks: Vec<StdWaker>,
119         callbacks_with_state: Vec<Box<dyn Fn(&Arc<Mutex<FutureState>>) -> () + Send>>,
120         complete: bool,
121         callbacks_made: bool,
122 }
123
124 fn complete_future(this: &Arc<Mutex<FutureState>>) -> bool {
125         let mut state_lock = this.lock().unwrap();
126         let state = &mut *state_lock;
127         for callback in state.callbacks.drain(..) {
128                 callback.call();
129                 state.callbacks_made = true;
130         }
131         for waker in state.std_future_callbacks.drain(..) {
132                 waker.0.wake_by_ref();
133         }
134         for callback in state.callbacks_with_state.drain(..) {
135                 (callback)(this);
136         }
137         state.complete = true;
138         state.callbacks_made
139 }
140
141 /// A simple future which can complete once, and calls some callback(s) when it does so.
142 ///
143 /// Clones can be made and all futures cloned from the same source will complete at the same time.
144 #[derive(Clone)]
145 pub struct Future {
146         state: Arc<Mutex<FutureState>>,
147 }
148
149 impl Future {
150         /// Registers a callback to be called upon completion of this future. If the future has already
151         /// completed, the callback will be called immediately.
152         ///
153         /// This is not exported to bindings users, use the bindings-only `register_callback_fn` instead
154         pub fn register_callback(&self, callback: Box<dyn FutureCallback>) {
155                 let mut state = self.state.lock().unwrap();
156                 if state.complete {
157                         state.callbacks_made = true;
158                         mem::drop(state);
159                         callback.call();
160                 } else {
161                         state.callbacks.push(callback);
162                 }
163         }
164
165         // C bindings don't (currently) know how to map `Box<dyn Trait>`, and while it could add the
166         // following wrapper, doing it in the bindings is currently much more work than simply doing it
167         // here.
168         /// Registers a callback to be called upon completion of this future. If the future has already
169         /// completed, the callback will be called immediately.
170         #[cfg(c_bindings)]
171         pub fn register_callback_fn<F: 'static + FutureCallback>(&self, callback: F) {
172                 self.register_callback(Box::new(callback));
173         }
174
175         /// Waits until this [`Future`] completes.
176         #[cfg(feature = "std")]
177         pub fn wait(self) {
178                 Sleeper::from_single_future(self).wait();
179         }
180
181         /// Waits until this [`Future`] completes or the given amount of time has elapsed.
182         ///
183         /// Returns true if the [`Future`] completed, false if the time elapsed.
184         #[cfg(feature = "std")]
185         pub fn wait_timeout(self, max_wait: Duration) -> bool {
186                 Sleeper::from_single_future(self).wait_timeout(max_wait)
187         }
188
189         #[cfg(test)]
190         pub fn poll_is_complete(&self) -> bool {
191                 let mut state = self.state.lock().unwrap();
192                 if state.complete {
193                         state.callbacks_made = true;
194                         true
195                 } else { false }
196         }
197 }
198
199 use core::task::Waker;
200 struct StdWaker(pub Waker);
201
202 /// This is not exported to bindings users as Rust Futures aren't usable in language bindings.
203 impl<'a> StdFuture for Future {
204         type Output = ();
205
206         fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
207                 let mut state = self.state.lock().unwrap();
208                 if state.complete {
209                         state.callbacks_made = true;
210                         Poll::Ready(())
211                 } else {
212                         let waker = cx.waker().clone();
213                         state.std_future_callbacks.push(StdWaker(waker));
214                         Poll::Pending
215                 }
216         }
217 }
218
219 /// A struct which can be used to select across many [`Future`]s at once without relying on a full
220 /// async context.
221 #[cfg(feature = "std")]
222 pub struct Sleeper {
223         notifiers: Vec<Arc<Mutex<FutureState>>>,
224 }
225
226 #[cfg(feature = "std")]
227 impl Sleeper {
228         /// Constructs a new sleeper from one future, allowing blocking on it.
229         pub fn from_single_future(future: Future) -> Self {
230                 Self { notifiers: vec![future.state] }
231         }
232         /// Constructs a new sleeper from two futures, allowing blocking on both at once.
233         // Note that this is the common case - a ChannelManager and ChainMonitor.
234         pub fn from_two_futures(fut_a: Future, fut_b: Future) -> Self {
235                 Self { notifiers: vec![fut_a.state, fut_b.state] }
236         }
237         /// Constructs a new sleeper on many futures, allowing blocking on all at once.
238         pub fn new(futures: Vec<Future>) -> Self {
239                 Self { notifiers: futures.into_iter().map(|f| f.state).collect() }
240         }
241         /// Prepares to go into a wait loop body, creating a condition variable which we can block on
242         /// and an `Arc<Mutex<Option<_>>>` which gets set to the waking `Future`'s state prior to the
243         /// condition variable being woken.
244         fn setup_wait(&self) -> (Arc<Condvar>, Arc<Mutex<Option<Arc<Mutex<FutureState>>>>>) {
245                 let cv = Arc::new(Condvar::new());
246                 let notified_fut_mtx = Arc::new(Mutex::new(None));
247                 {
248                         for notifier_mtx in self.notifiers.iter() {
249                                 let cv_ref = Arc::clone(&cv);
250                                 let notified_fut_ref = Arc::clone(&notified_fut_mtx);
251                                 let mut notifier = notifier_mtx.lock().unwrap();
252                                 if notifier.complete {
253                                         *notified_fut_mtx.lock().unwrap() = Some(Arc::clone(&notifier_mtx));
254                                         break;
255                                 }
256                                 notifier.callbacks_with_state.push(Box::new(move |notifier_ref| {
257                                         *notified_fut_ref.lock().unwrap() = Some(Arc::clone(notifier_ref));
258                                         cv_ref.notify_all();
259                                 }));
260                         }
261                 }
262                 (cv, notified_fut_mtx)
263         }
264
265         /// Wait until one of the [`Future`]s registered with this [`Sleeper`] has completed.
266         pub fn wait(&self) {
267                 let (cv, notified_fut_mtx) = self.setup_wait();
268                 let notified_fut = cv.wait_while(notified_fut_mtx.lock().unwrap(), |fut_opt| fut_opt.is_none())
269                         .unwrap().take().expect("CV wait shouldn't have returned until the notifying future was set");
270                 notified_fut.lock().unwrap().callbacks_made = true;
271         }
272
273         /// Wait until one of the [`Future`]s registered with this [`Sleeper`] has completed or the
274         /// given amount of time has elapsed. Returns true if a [`Future`] completed, false if the time
275         /// elapsed.
276         pub fn wait_timeout(&self, max_wait: Duration) -> bool {
277                 let (cv, notified_fut_mtx) = self.setup_wait();
278                 let notified_fut =
279                         match cv.wait_timeout_while(notified_fut_mtx.lock().unwrap(), max_wait, |fut_opt| fut_opt.is_none()) {
280                                 Ok((_, e)) if e.timed_out() => return false,
281                                 Ok((mut notified_fut, _)) =>
282                                         notified_fut.take().expect("CV wait shouldn't have returned until the notifying future was set"),
283                                 Err(_) => panic!("Previous panic while a lock was held led to a lock panic"),
284                         };
285                 notified_fut.lock().unwrap().callbacks_made = true;
286                 true
287         }
288 }
289
290 #[cfg(test)]
291 mod tests {
292         use super::*;
293         use core::sync::atomic::{AtomicBool, Ordering};
294         use core::future::Future as FutureTrait;
295         use core::task::{Context, Poll, RawWaker, RawWakerVTable, Waker};
296
297         #[test]
298         fn notifier_pre_notified_future() {
299                 // Previously, if we generated a future after a `Notifier` had been notified, the future
300                 // would never complete. This tests this behavior, ensuring the future instead completes
301                 // immediately.
302                 let notifier = Notifier::new();
303                 notifier.notify();
304
305                 let callback = Arc::new(AtomicBool::new(false));
306                 let callback_ref = Arc::clone(&callback);
307                 notifier.get_future().register_callback(Box::new(move || assert!(!callback_ref.fetch_or(true, Ordering::SeqCst))));
308                 assert!(callback.load(Ordering::SeqCst));
309         }
310
311         #[test]
312         fn notifier_future_completes_wake() {
313                 // Previously, if we were only using the `Future` interface to learn when a `Notifier` has
314                 // been notified, we'd never mark the notifier as not-awaiting-notify. This caused the
315                 // `lightning-background-processor` to persist in a tight loop.
316                 let notifier = Notifier::new();
317
318                 // First check the simple case, ensuring if we get notified a new future isn't woken until
319                 // a second `notify`.
320                 let callback = Arc::new(AtomicBool::new(false));
321                 let callback_ref = Arc::clone(&callback);
322                 notifier.get_future().register_callback(Box::new(move || assert!(!callback_ref.fetch_or(true, Ordering::SeqCst))));
323                 assert!(!callback.load(Ordering::SeqCst));
324
325                 notifier.notify();
326                 assert!(callback.load(Ordering::SeqCst));
327
328                 let callback = Arc::new(AtomicBool::new(false));
329                 let callback_ref = Arc::clone(&callback);
330                 notifier.get_future().register_callback(Box::new(move || assert!(!callback_ref.fetch_or(true, Ordering::SeqCst))));
331                 assert!(!callback.load(Ordering::SeqCst));
332
333                 notifier.notify();
334                 assert!(callback.load(Ordering::SeqCst));
335
336                 // Then check the case where the future is fetched before the notification, but a callback
337                 // is only registered after the `notify`, ensuring that it is still sufficient to ensure we
338                 // don't get an instant-wake when we get a new future.
339                 let future = notifier.get_future();
340                 notifier.notify();
341
342                 let callback = Arc::new(AtomicBool::new(false));
343                 let callback_ref = Arc::clone(&callback);
344                 future.register_callback(Box::new(move || assert!(!callback_ref.fetch_or(true, Ordering::SeqCst))));
345                 assert!(callback.load(Ordering::SeqCst));
346
347                 let callback = Arc::new(AtomicBool::new(false));
348                 let callback_ref = Arc::clone(&callback);
349                 notifier.get_future().register_callback(Box::new(move || assert!(!callback_ref.fetch_or(true, Ordering::SeqCst))));
350                 assert!(!callback.load(Ordering::SeqCst));
351         }
352
353         #[test]
354         fn new_future_wipes_notify_bit() {
355                 // Previously, if we were only using the `Future` interface to learn when a `Notifier` has
356                 // been notified, we'd never mark the notifier as not-awaiting-notify if a `Future` is
357                 // fetched after the notify bit has been set.
358                 let notifier = Notifier::new();
359                 notifier.notify();
360
361                 let callback = Arc::new(AtomicBool::new(false));
362                 let callback_ref = Arc::clone(&callback);
363                 notifier.get_future().register_callback(Box::new(move || assert!(!callback_ref.fetch_or(true, Ordering::SeqCst))));
364                 assert!(callback.load(Ordering::SeqCst));
365
366                 let callback = Arc::new(AtomicBool::new(false));
367                 let callback_ref = Arc::clone(&callback);
368                 notifier.get_future().register_callback(Box::new(move || assert!(!callback_ref.fetch_or(true, Ordering::SeqCst))));
369                 assert!(!callback.load(Ordering::SeqCst));
370
371                 notifier.notify();
372                 assert!(callback.load(Ordering::SeqCst));
373         }
374
375         #[cfg(feature = "std")]
376         #[test]
377         fn test_wait_timeout() {
378                 use crate::sync::Arc;
379                 use std::thread;
380
381                 let persistence_notifier = Arc::new(Notifier::new());
382                 let thread_notifier = Arc::clone(&persistence_notifier);
383
384                 let exit_thread = Arc::new(AtomicBool::new(false));
385                 let exit_thread_clone = exit_thread.clone();
386                 thread::spawn(move || {
387                         loop {
388                                 thread_notifier.notify();
389                                 if exit_thread_clone.load(Ordering::SeqCst) {
390                                         break
391                                 }
392                         }
393                 });
394
395                 // Check that we can block indefinitely until updates are available.
396                 let _ = persistence_notifier.get_future().wait();
397
398                 // Check that the Notifier will return after the given duration if updates are
399                 // available.
400                 loop {
401                         if persistence_notifier.get_future().wait_timeout(Duration::from_millis(100)) {
402                                 break
403                         }
404                 }
405
406                 exit_thread.store(true, Ordering::SeqCst);
407
408                 // Check that the Notifier will return after the given duration even if no updates
409                 // are available.
410                 loop {
411                         if !persistence_notifier.get_future().wait_timeout(Duration::from_millis(100)) {
412                                 break
413                         }
414                 }
415         }
416
417         #[cfg(feature = "std")]
418         #[test]
419         fn test_state_drops() {
420                 // Previously, there was a leak if a `Notifier` was `drop`ed without ever being notified
421                 // but after having been slept-on. This tests for that leak.
422                 use crate::sync::Arc;
423                 use std::thread;
424
425                 let notifier_a = Arc::new(Notifier::new());
426                 let notifier_b = Arc::new(Notifier::new());
427
428                 let thread_notifier_a = Arc::clone(&notifier_a);
429
430                 let future_a = notifier_a.get_future();
431                 let future_state_a = Arc::downgrade(&future_a.state);
432
433                 let future_b = notifier_b.get_future();
434                 let future_state_b = Arc::downgrade(&future_b.state);
435
436                 let join_handle = thread::spawn(move || {
437                         // Let the other thread get to the wait point, then notify it.
438                         std::thread::sleep(Duration::from_millis(50));
439                         thread_notifier_a.notify();
440                 });
441
442                 // Wait on the other thread to finish its sleep, note that the leak only happened if we
443                 // actually have to sleep here, not if we immediately return.
444                 Sleeper::from_two_futures(future_a, future_b).wait();
445
446                 join_handle.join().unwrap();
447
448                 // then drop the notifiers and make sure the future states are gone.
449                 mem::drop(notifier_a);
450                 mem::drop(notifier_b);
451
452                 assert!(future_state_a.upgrade().is_none() && future_state_b.upgrade().is_none());
453         }
454
455         #[test]
456         fn test_future_callbacks() {
457                 let future = Future {
458                         state: Arc::new(Mutex::new(FutureState {
459                                 callbacks: Vec::new(),
460                                 std_future_callbacks: Vec::new(),
461                                 callbacks_with_state: Vec::new(),
462                                 complete: false,
463                                 callbacks_made: false,
464                         }))
465                 };
466                 let callback = Arc::new(AtomicBool::new(false));
467                 let callback_ref = Arc::clone(&callback);
468                 future.register_callback(Box::new(move || assert!(!callback_ref.fetch_or(true, Ordering::SeqCst))));
469
470                 assert!(!callback.load(Ordering::SeqCst));
471                 complete_future(&future.state);
472                 assert!(callback.load(Ordering::SeqCst));
473                 complete_future(&future.state);
474         }
475
476         #[test]
477         fn test_pre_completed_future_callbacks() {
478                 let future = Future {
479                         state: Arc::new(Mutex::new(FutureState {
480                                 callbacks: Vec::new(),
481                                 callbacks_with_state: Vec::new(),
482                                 complete: false,
483                                 callbacks_made: false,
484                         }))
485                 };
486                 complete_future(&future.state);
487
488                 let callback = Arc::new(AtomicBool::new(false));
489                 let callback_ref = Arc::clone(&callback);
490                 future.register_callback(Box::new(move || assert!(!callback_ref.fetch_or(true, Ordering::SeqCst))));
491
492                 assert!(callback.load(Ordering::SeqCst));
493                 assert!(future.state.lock().unwrap().callbacks.is_empty());
494         }
495
496         // Rather annoyingly, there's no safe way in Rust std to construct a Waker despite it being
497         // totally possible to construct from a trait implementation (though somewhat less efficient
498         // compared to a raw VTable). Instead, we have to write out a lot of boilerplate to build a
499         // waker, which we do here with a trivial Arc<AtomicBool> data element to track woke-ness.
500         const WAKER_V_TABLE: RawWakerVTable = RawWakerVTable::new(waker_clone, wake, wake_by_ref, drop);
501         unsafe fn wake_by_ref(ptr: *const ()) { let p = ptr as *const Arc<AtomicBool>; assert!(!(*p).fetch_or(true, Ordering::SeqCst)); }
502         unsafe fn drop(ptr: *const ()) { let p = ptr as *mut Arc<AtomicBool>; let _freed = Box::from_raw(p); }
503         unsafe fn wake(ptr: *const ()) { wake_by_ref(ptr); drop(ptr); }
504         unsafe fn waker_clone(ptr: *const ()) -> RawWaker {
505                 let p = ptr as *const Arc<AtomicBool>;
506                 RawWaker::new(Box::into_raw(Box::new(Arc::clone(&*p))) as *const (), &WAKER_V_TABLE)
507         }
508
509         fn create_waker() -> (Arc<AtomicBool>, Waker) {
510                 let a = Arc::new(AtomicBool::new(false));
511                 let waker = unsafe { Waker::from_raw(waker_clone((&a as *const Arc<AtomicBool>) as *const ())) };
512                 (a, waker)
513         }
514
515         #[test]
516         fn test_future() {
517                 let mut future = Future {
518                         state: Arc::new(Mutex::new(FutureState {
519                                 callbacks: Vec::new(),
520                                 std_future_callbacks: Vec::new(),
521                                 callbacks_with_state: Vec::new(),
522                                 complete: false,
523                                 callbacks_made: false,
524                         }))
525                 };
526                 let mut second_future = Future { state: Arc::clone(&future.state) };
527
528                 let (woken, waker) = create_waker();
529                 assert_eq!(Pin::new(&mut future).poll(&mut Context::from_waker(&waker)), Poll::Pending);
530                 assert!(!woken.load(Ordering::SeqCst));
531
532                 let (second_woken, second_waker) = create_waker();
533                 assert_eq!(Pin::new(&mut second_future).poll(&mut Context::from_waker(&second_waker)), Poll::Pending);
534                 assert!(!second_woken.load(Ordering::SeqCst));
535
536                 complete_future(&future.state);
537                 assert!(woken.load(Ordering::SeqCst));
538                 assert!(second_woken.load(Ordering::SeqCst));
539                 assert_eq!(Pin::new(&mut future).poll(&mut Context::from_waker(&waker)), Poll::Ready(()));
540                 assert_eq!(Pin::new(&mut second_future).poll(&mut Context::from_waker(&second_waker)), Poll::Ready(()));
541         }
542
543         #[test]
544         #[cfg(feature = "std")]
545         fn test_dropped_future_doesnt_count() {
546                 // Tests that if a Future gets drop'd before it is poll()ed `Ready` it doesn't count as
547                 // having been woken, leaving the notify-required flag set.
548                 let notifier = Notifier::new();
549                 notifier.notify();
550
551                 // If we get a future and don't touch it we're definitely still notify-required.
552                 notifier.get_future();
553                 assert!(notifier.get_future().wait_timeout(Duration::from_millis(1)));
554                 assert!(!notifier.get_future().wait_timeout(Duration::from_millis(1)));
555
556                 // Even if we poll'd once but didn't observe a `Ready`, we should be notify-required.
557                 let mut future = notifier.get_future();
558                 let (woken, waker) = create_waker();
559                 assert_eq!(Pin::new(&mut future).poll(&mut Context::from_waker(&waker)), Poll::Pending);
560
561                 notifier.notify();
562                 assert!(woken.load(Ordering::SeqCst));
563                 assert!(notifier.get_future().wait_timeout(Duration::from_millis(1)));
564
565                 // However, once we do poll `Ready` it should wipe the notify-required flag.
566                 let mut future = notifier.get_future();
567                 let (woken, waker) = create_waker();
568                 assert_eq!(Pin::new(&mut future).poll(&mut Context::from_waker(&waker)), Poll::Pending);
569
570                 notifier.notify();
571                 assert!(woken.load(Ordering::SeqCst));
572                 assert_eq!(Pin::new(&mut future).poll(&mut Context::from_waker(&waker)), Poll::Ready(()));
573                 assert!(!notifier.get_future().wait_timeout(Duration::from_millis(1)));
574         }
575
576         #[test]
577         fn test_poll_post_notify_completes() {
578                 // Tests that if we have a future state that has completed, and we haven't yet requested a
579                 // new future, if we get a notify prior to requesting that second future it is generated
580                 // pre-completed.
581                 let notifier = Notifier::new();
582
583                 notifier.notify();
584                 let mut future = notifier.get_future();
585                 let (woken, waker) = create_waker();
586                 assert_eq!(Pin::new(&mut future).poll(&mut Context::from_waker(&waker)), Poll::Ready(()));
587                 assert!(!woken.load(Ordering::SeqCst));
588
589                 notifier.notify();
590                 let mut future = notifier.get_future();
591                 let (woken, waker) = create_waker();
592                 assert_eq!(Pin::new(&mut future).poll(&mut Context::from_waker(&waker)), Poll::Ready(()));
593                 assert!(!woken.load(Ordering::SeqCst));
594
595                 let mut future = notifier.get_future();
596                 let (woken, waker) = create_waker();
597                 assert_eq!(Pin::new(&mut future).poll(&mut Context::from_waker(&waker)), Poll::Pending);
598                 assert!(!woken.load(Ordering::SeqCst));
599
600                 notifier.notify();
601                 assert!(woken.load(Ordering::SeqCst));
602                 assert_eq!(Pin::new(&mut future).poll(&mut Context::from_waker(&waker)), Poll::Ready(()));
603         }
604
605         #[test]
606         fn test_poll_post_notify_completes_initial_notified() {
607                 // Identical to the previous test, but the first future completes via a wake rather than an
608                 // immediate `Poll::Ready`.
609                 let notifier = Notifier::new();
610
611                 let mut future = notifier.get_future();
612                 let (woken, waker) = create_waker();
613                 assert_eq!(Pin::new(&mut future).poll(&mut Context::from_waker(&waker)), Poll::Pending);
614
615                 notifier.notify();
616                 assert!(woken.load(Ordering::SeqCst));
617                 assert_eq!(Pin::new(&mut future).poll(&mut Context::from_waker(&waker)), Poll::Ready(()));
618
619                 notifier.notify();
620                 let mut future = notifier.get_future();
621                 let (woken, waker) = create_waker();
622                 assert_eq!(Pin::new(&mut future).poll(&mut Context::from_waker(&waker)), Poll::Ready(()));
623                 assert!(!woken.load(Ordering::SeqCst));
624
625                 let mut future = notifier.get_future();
626                 let (woken, waker) = create_waker();
627                 assert_eq!(Pin::new(&mut future).poll(&mut Context::from_waker(&waker)), Poll::Pending);
628                 assert!(!woken.load(Ordering::SeqCst));
629
630                 notifier.notify();
631                 assert!(woken.load(Ordering::SeqCst));
632                 assert_eq!(Pin::new(&mut future).poll(&mut Context::from_waker(&waker)), Poll::Ready(()));
633         }
634
635         #[test]
636         #[cfg(feature = "std")]
637         fn test_multi_future_sleep() {
638                 // Tests the `Sleeper` with multiple futures.
639                 let notifier_a = Notifier::new();
640                 let notifier_b = Notifier::new();
641
642                 // Set both notifiers as woken without sleeping yet.
643                 notifier_a.notify();
644                 notifier_b.notify();
645                 Sleeper::from_two_futures(notifier_a.get_future(), notifier_b.get_future()).wait();
646
647                 // One future has woken us up, but the other should still have a pending notification.
648                 Sleeper::from_two_futures(notifier_a.get_future(), notifier_b.get_future()).wait();
649
650                 // However once we've slept twice, we should no longer have any pending notifications
651                 assert!(!Sleeper::from_two_futures(notifier_a.get_future(), notifier_b.get_future())
652                         .wait_timeout(Duration::from_millis(10)));
653
654                 // Test ordering somewhat more.
655                 notifier_a.notify();
656                 Sleeper::from_two_futures(notifier_a.get_future(), notifier_b.get_future()).wait();
657         }
658
659         #[test]
660         #[cfg(feature = "std")]
661         fn sleeper_with_pending_callbacks() {
662                 // This is similar to the above `test_multi_future_sleep` test, but in addition registers
663                 // "normal" callbacks which will cause the futures to assume notification has occurred,
664                 // rather than waiting for a woken sleeper.
665                 let notifier_a = Notifier::new();
666                 let notifier_b = Notifier::new();
667
668                 // Set both notifiers as woken without sleeping yet.
669                 notifier_a.notify();
670                 notifier_b.notify();
671
672                 // After sleeping one future (not guaranteed which one, however) will have its notification
673                 // bit cleared.
674                 Sleeper::from_two_futures(notifier_a.get_future(), notifier_b.get_future()).wait();
675
676                 // By registering a callback on the futures for both notifiers, one will complete
677                 // immediately, but one will remain tied to the notifier, and will complete once the
678                 // notifier is next woken, which will be considered the completion of the notification.
679                 let callback_a = Arc::new(AtomicBool::new(false));
680                 let callback_b = Arc::new(AtomicBool::new(false));
681                 let callback_a_ref = Arc::clone(&callback_a);
682                 let callback_b_ref = Arc::clone(&callback_b);
683                 notifier_a.get_future().register_callback(Box::new(move || assert!(!callback_a_ref.fetch_or(true, Ordering::SeqCst))));
684                 notifier_b.get_future().register_callback(Box::new(move || assert!(!callback_b_ref.fetch_or(true, Ordering::SeqCst))));
685                 assert!(callback_a.load(Ordering::SeqCst) ^ callback_b.load(Ordering::SeqCst));
686
687                 // If we now notify both notifiers again, the other callback will fire, completing the
688                 // notification, and we'll be back to one pending notification.
689                 notifier_a.notify();
690                 notifier_b.notify();
691
692                 assert!(callback_a.load(Ordering::SeqCst) && callback_b.load(Ordering::SeqCst));
693                 Sleeper::from_two_futures(notifier_a.get_future(), notifier_b.get_future()).wait();
694                 assert!(!Sleeper::from_two_futures(notifier_a.get_future(), notifier_b.get_future())
695                         .wait_timeout(Duration::from_millis(10)));
696         }
697 }