1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
// Copyright 2024 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

//! Implements a waker list.
//!
//! # Example:
//!
//! ```no_run
//! fn foo() {
//!     let waker_list = WakerList::new();
//!
//!     let waker_entry = pin!(waker_list.new_entry());
//!     poll_fn(|cx| {
//!         if (ready) {
//!             Poll::Ready(())
//!         } else {
//!             waker_entry.add(cx.waker().clone());
//!             Poll::Pending
//!         }
//!     }).await;
//!
//!     // Elsewhere...
//!     for waker in waker_list.drain() {
//!         waker.wake();
//!     }
//! }
//! ```

use std::pin::Pin;
use std::sync::{Arc, Mutex, MutexGuard};
use std::task::Waker;

/// A waker list.
// WakerList is implemented as an intrusive doubly linked list.  Typical use should avoid any
// additional heap allocations after creation, as the nodes of the list are stored as part of the
// caller's future.
pub struct WakerList(Arc<Mutex<Inner>>);

impl WakerList {
    /// Returns a new waker list.
    pub fn new() -> Self {
        Self(Arc::new(Mutex::new(Inner { head: std::ptr::null_mut(), count: 0 })))
    }

    /// Returns a new entry that can be later added to this list.
    pub fn new_entry(&self) -> WakerEntry {
        WakerEntry {
            list: self.0.clone(),
            node: Node { next: std::ptr::null_mut(), prev: std::ptr::null_mut(), waker: None },
        }
    }

    /// Returns the number of wakers in the list.
    pub fn len(&self) -> usize {
        self.0.lock().unwrap().count
    }

    /// Returns an iterator that will drain all wakers.  Whilst the drainer exists, a lock is held
    /// which will prevent new wakers from being added to the list, so depending on your use case,
    /// you might wish to collect the wakers before calling `wake` on each waker.  NOTE: If the
    /// drainer is dropped, this will *not* drain elements not visited.
    pub fn drain(&self) -> Drainer<'_> {
        Drainer(self.0.lock().unwrap())
    }
}

struct Inner {
    head: *mut Node,
    count: usize,
}

// SAFETY: Safe because we always access `head` whilst holding the list lock.
unsafe impl Send for Inner {}

/// A waker entry that can be added to a list.
pub struct WakerEntry {
    list: Arc<Mutex<Inner>>,
    node: Node,
}

impl WakerEntry {
    /// Adds this entry to the list.
    pub fn add(self: Pin<&mut Self>, waker: Waker) {
        // SAFETY: We never move the data out.
        let this = unsafe { self.get_unchecked_mut() };
        let mut inner = this.list.lock().unwrap();
        this.node.add(&mut *inner, waker);
    }
}

impl Drop for WakerEntry {
    fn drop(&mut self) {
        self.node.remove(&mut *self.list.lock().unwrap());
    }
}

// The members here must only be accessed whilst holding the mutex on the list.
struct Node {
    next: *mut Node,
    prev: *mut Node,
    waker: Option<Waker>,
}

// SAFETY: Safe because we always access all mebers of `Node` whilst holding the list lock.
unsafe impl Send for Node {}

impl Node {
    fn add(&mut self, inner: &mut Inner, waker: Waker) {
        if self.waker.is_none() {
            self.prev = std::ptr::null_mut();
            self.next = inner.head;
            inner.head = self;
            if !self.next.is_null() {
                // SAFETY: Safe because we have exclusive access to `Inner`.
                unsafe {
                    (*self.next).prev = self;
                }
            }
            inner.count += 1;
        }
        self.waker = Some(waker);
    }

    fn remove(&mut self, inner: &mut Inner) -> Option<Waker> {
        if self.waker.is_none() {
            return None;
        }
        if !self.next.is_null() {
            // SAFETY: Safe because we have exclusive access to `Inner`.
            unsafe { (*self.next).prev = self.prev };
        }
        if self.prev.is_null() {
            inner.head = self.next;
        } else {
            // SAFETY: Safe because we have exclusive access to `Inner`.
            unsafe { (*self.prev).next = self.next };
        }
        self.prev = std::ptr::null_mut();
        self.next = std::ptr::null_mut();
        inner.count -= 1;
        self.waker.take()
    }
}

/// An iterator that will drain waiters.
pub struct Drainer<'a>(MutexGuard<'a, Inner>);

impl Iterator for Drainer<'_> {
    type Item = Waker;
    fn next(&mut self) -> Option<Self::Item> {
        if self.0.head.is_null() {
            None
        } else {
            // SAFETY: Safe because we have exclusive access to `Inner`.
            unsafe { &mut (*self.0.head) }.remove(&mut self.0)
        }
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        (self.0.count, Some(self.0.count))
    }
}

impl ExactSizeIterator for Drainer<'_> {
    fn len(&self) -> usize {
        self.0.count
    }
}

#[cfg(all(target_os = "fuchsia", test))]
mod tests {
    use super::WakerList;
    use crate::TestExecutor;
    use assert_matches::assert_matches;
    use futures::stream::FuturesUnordered;
    use futures::task::noop_waker;
    use futures::{FutureExt, StreamExt};
    use std::future::poll_fn;
    use std::pin::pin;
    use std::sync::atomic::{AtomicU64, Ordering};
    use std::task::{Context, Poll};

    #[test]
    fn test_waker_list_can_waker_multiple_wakers() {
        let mut executor = TestExecutor::new();
        let waker_list = WakerList::new();

        static COUNT: u64 = 10;

        let counter = AtomicU64::new(0);

        // Use FuturesUnordered so that futures are only polled when explicitly woken.
        let mut futures = FuturesUnordered::new();

        for _ in 0..COUNT {
            futures.push(
                async {
                    let mut entry = pin!(waker_list.new_entry());
                    poll_fn(|cx: &mut Context<'_>| {
                        if counter.fetch_add(1, Ordering::Relaxed) < COUNT {
                            entry.as_mut().add(cx.waker().clone());
                            Poll::Pending
                        } else {
                            Poll::Ready(())
                        }
                    })
                    .await;
                }
                .boxed(),
            );
        }

        assert_eq!(executor.run_until_stalled(&mut futures.next()), Poll::Pending);

        assert_eq!(counter.load(Ordering::Relaxed), COUNT);
        assert_eq!(waker_list.len(), COUNT as usize);

        let drainer = waker_list.drain();
        assert_eq!(drainer.len(), COUNT as usize);

        for waker in drainer {
            waker.wake();
        }

        assert_matches!(
            executor.run_until_stalled(&mut futures.collect::<Vec<_>>()),
            Poll::Ready(_)
        );
        assert_eq!(counter.load(Ordering::Relaxed), COUNT * 2);
    }

    #[test]
    fn test_dropping_waker_entry_removes_from_list() {
        let waker_list = WakerList::new();

        let entry1 = pin!(waker_list.new_entry());
        entry1.add(noop_waker());

        {
            let entry2 = pin!(waker_list.new_entry());
            entry2.add(noop_waker());

            assert_eq!(waker_list.len(), 2);
        }

        assert_eq!(waker_list.len(), 1);
        assert_eq!(waker_list.drain().count(), 1);

        assert_eq!(waker_list.len(), 0);

        let entry3 = pin!(waker_list.new_entry());
        entry3.add(noop_waker());

        assert_eq!(waker_list.len(), 1);
    }

    #[test]
    fn test_waker_can_be_added_multiple_times() {
        let waker_list = WakerList::new();

        let mut entry1 = pin!(waker_list.new_entry());
        entry1.as_mut().add(noop_waker());

        let mut entry2 = pin!(waker_list.new_entry());
        entry2.as_mut().add(noop_waker());

        assert_eq!(waker_list.len(), 2);
        assert_eq!(waker_list.drain().count(), 2);
        assert_eq!(waker_list.len(), 0);

        entry1.add(noop_waker());
        entry2.add(noop_waker());

        assert_eq!(waker_list.len(), 2);
        assert_eq!(waker_list.drain().count(), 2);
        assert_eq!(waker_list.len(), 0);
    }
}