async-utils 0.1.1

nothing to see here yet :)
Documentation
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
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
use std::{
    cell::{Cell, UnsafeCell},
    fmt,
    future::Future,
    marker::PhantomPinned,
    mem,
    ops::{Deref, DerefMut},
    panic::{RefUnwindSafe, UnwindSafe},
    pin::Pin,
    ptr::{self, NonNull},
    sync::atomic::{AtomicUsize, Ordering},
    task::{Context, Poll, Waker},
};

use crate::sync::{
    atomic::full_fence,
    mutex::{Mutex, MutexFamily, MutexGuardType, StdMutex},
};

pub struct Event<M: MutexFamily = StdMutex> {
    /// The number of notified entries, or `usize::MAX` if all of them have been notified.
    ///
    /// If there are no entries, this value is set to `usize::MAX`.
    notified: AtomicUsize,

    /// A linked list holding registered listeners.
    list: M::Mutex<List>,
}

unsafe impl<M: MutexFamily> Send for Event<M> {}
unsafe impl<M: MutexFamily> Sync for Event<M> {}

impl<M: MutexFamily> UnwindSafe for Event<M> {}
impl<M: MutexFamily> RefUnwindSafe for Event<M> {}

impl<M: MutexFamily> Event<M> {
    #[inline]
    pub fn new() -> Self {
        Self {
            notified: AtomicUsize::new(usize::MAX),
            list: M::new(List::new()),
        }
    }

    #[inline]
    fn lock(&self) -> ListGuard<'_, M> {
        ListGuard {
            event: self,
            guard: self.list.lock(),
        }
    }

    #[cold]
    pub fn listener(&self) -> EventListener<'_, M> {
        EventListener {
            event: self,
            state: ListenerState::Init,
            entry: UnsafeCell::new(Entry::new()),
        }
    }

    #[inline]
    pub fn notify(&self, n: usize) {
        // Make sure the notification comes after whatever triggered it.
        full_fence();
        self.notify_relaxed(n)
    }

    #[inline]
    pub fn notify_relaxed(&self, n: usize) {
        // Notify if there is at least one unnotified listener and the number of notified
        // listeners is less than `n`.
        if self.notified.load(Ordering::Acquire) < n {
            self.lock().notify(n);
        }
    }

    #[inline]
    pub fn notify_additional(&self, n: usize) {
        // Make sure the notification comes after whatever triggered it.
        full_fence();
        self.notify_additional_relaxed(n);
    }

    #[inline]
    pub fn notify_additional_relaxed(&self, n: usize) {
        // Notify if there is at least one unnotified listener.
        if self.notified.load(Ordering::Acquire) < usize::MAX {
            self.lock().notify_additional(n);
        }
    }
}

impl<M: MutexFamily> fmt::Debug for Event<M> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.pad("Event { .. }")
    }
}

impl<M: MutexFamily> Default for Event<M> {
    fn default() -> Self {
        Event::new()
    }
}

#[derive(Debug, Copy, Clone, PartialEq, Eq)]
enum ListenerState {
    Init,
    Listening,
    Done,
}

pub struct EventListener<'a, M: MutexFamily> {
    event: &'a Event<M>,
    state: ListenerState,
    entry: UnsafeCell<Entry>,
}

unsafe impl<M: MutexFamily> Send for EventListener<'_, M> {}
unsafe impl<M: MutexFamily> Sync for EventListener<'_, M> {}

impl<M: MutexFamily> UnwindSafe for EventListener<'_, M> {}
impl<M: MutexFamily> RefUnwindSafe for EventListener<'_, M> {}

impl<M: MutexFamily> EventListener<'_, M> {
    #[inline]
    fn project(self: Pin<&mut Self>) -> (&Event<M>, &mut ListenerState, Pin<&UnsafeCell<Entry>>) {
        fn is_unpin<T: Unpin>() {}

        unsafe {
            is_unpin::<&Event<M>>();
            is_unpin::<ListenerState>();

            let this = self.get_unchecked_mut();
            (this.event, &mut this.state, Pin::new_unchecked(&this.entry))
        }
    }

    pub fn listen(self: Pin<&mut Self>) {
        let (event, state, entry) = self.project();

        if *state == ListenerState::Init {
            event.lock().insert(entry, None);
            *state = ListenerState::Listening;
        }

        full_fence();
    }

    #[inline]
    pub fn listens_to(&self, event: &Event<M>) -> bool {
        ptr::eq(self.event, event)
    }

    #[inline]
    pub fn same_event(&self, other: &EventListener<'_, M>) -> bool {
        ptr::eq(self.event, other.event)
    }
}

impl<M: MutexFamily> Future for EventListener<'_, M> {
    type Output = ();

    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
        let (inner, listener_state, entry) = self.project();

        if *listener_state == ListenerState::Done {
            return Poll::Ready(());
        }

        let mut list = inner.lock();

        if *listener_state == ListenerState::Init {
            list.insert(entry, Some(cx.waker().clone()));
            *listener_state = ListenerState::Listening;

            full_fence();

            return Poll::Pending;
        }

        let entry = unsafe { &mut *entry.get_ref().get() };
        let state = &mut entry.state;

        // Do a dummy replace operation in order to take out the state.
        match state.replace(State::Notified(false)) {
            State::Notified(_) => {
                // If this listener has been notified, remove it from the list and return.
                let entry = unsafe { NonNull::new_unchecked(entry as *mut _) };
                list.remove(entry);
                *listener_state = ListenerState::Done;

                drop(list);

                return Poll::Ready(());
            }
            State::Created => {
                // If the listener was just created, put it in the `Polling` state.
                state.set(State::Polling(cx.waker().clone()));
            }
            State::Polling(w) => {
                // If the listener was in the `Polling` state, update the waker.
                if w.will_wake(cx.waker()) {
                    state.set(State::Polling(w));
                } else {
                    state.set(State::Polling(cx.waker().clone()));
                }
            }
        }

        Poll::Pending
    }
}

impl<M: MutexFamily> Drop for EventListener<'_, M> {
    fn drop(&mut self) {
        // If this listener has never picked up a notification...
        if self.state == ListenerState::Listening {
            let mut list = self.event.lock();
            let entry = unsafe { NonNull::new_unchecked(self.entry.get()) };

            // But if a notification was delivered to it...
            if let State::Notified(additional) = list.remove(entry) {
                // Then pass it on to another active listener.
                if additional {
                    list.notify_additional(1);
                } else {
                    list.notify(1);
                }
            }

            self.state = ListenerState::Done;
        }
    }
}

/// A guard holding the linked list locked.
struct ListGuard<'a, M: MutexFamily> {
    /// A reference to [`Event`]'s state.
    event: &'a Event<M>,

    /// The actual guard that acquired the linked list.
    guard: MutexGuardType<'a, M, List>,
}

impl<M: MutexFamily> Drop for ListGuard<'_, M> {
    #[inline]
    fn drop(&mut self) {
        let list = &mut **self;

        // Update the atomic `notified` counter.
        let notified = if list.notified < list.len {
            list.notified
        } else {
            usize::MAX
        };

        self.event.notified.store(notified, Ordering::Release);
    }
}

impl<M: MutexFamily> Deref for ListGuard<'_, M> {
    type Target = List;

    #[inline]
    fn deref(&self) -> &List {
        &self.guard
    }
}

impl<M: MutexFamily> DerefMut for ListGuard<'_, M> {
    #[inline]
    fn deref_mut(&mut self) -> &mut List {
        &mut self.guard
    }
}

/// The state of a listener.
enum State {
    /// It has just been created.
    Created,

    /// It has received a notification.
    ///
    /// The `bool` is `true` if this was an "additional" notification.
    Notified(bool),

    /// An async task is polling it.
    Polling(Waker),
}

impl State {
    /// Returns `true` if this is the `Notified` state.
    #[inline]
    fn is_notified(&self) -> bool {
        match self {
            State::Notified(_) => true,
            State::Created | State::Polling(_) => false,
        }
    }
}

/// An entry representing a registered listener.
struct Entry {
    /// THe state of this listener.
    state: Cell<State>,

    /// Previous entry in the linked list.
    prev: Cell<Option<NonNull<Entry>>>,

    /// Next entry in the linked list.
    next: Cell<Option<NonNull<Entry>>>,

    /// Entries are pinned in memory.
    _pinned: PhantomPinned,
}

impl Entry {
    #[inline]
    const fn new() -> Self {
        Self {
            state: Cell::new(State::Created),
            prev: Cell::new(None),
            next: Cell::new(None),
            _pinned: PhantomPinned,
        }
    }
}

/// A linked list of entries.
struct List {
    /// First entry in the list.
    head: Option<NonNull<Entry>>,

    /// Last entry in the list.
    tail: Option<NonNull<Entry>>,

    /// The first unnotified entry in the list.
    start: Option<NonNull<Entry>>,

    /// Total number of entries in the list.
    len: usize,

    /// The number of notified entries in the list.
    notified: usize,
}

unsafe impl Send for List {}

impl List {
    #[inline]
    const fn new() -> Self {
        Self {
            head: None,
            tail: None,
            start: None,
            len: 0,
            notified: 0,
        }
    }

    /// Inserts a pinned entry into the list.
    fn insert(&mut self, entry: Pin<&UnsafeCell<Entry>>, waker: Option<Waker>) {
        unsafe {
            let state = waker.map(State::Polling).unwrap_or(State::Created);
            let entry = &mut *entry.get_ref().get();

            *entry = Entry {
                state: Cell::new(state),
                prev: Cell::new(self.tail),
                next: Cell::new(None),
                _pinned: PhantomPinned,
            };

            let entry = NonNull::new_unchecked(entry as *mut _);

            // Replace the tail with the new entry.
            match mem::replace(&mut self.tail, Some(entry)) {
                None => self.head = Some(entry),
                Some(t) => t.as_ref().next.set(Some(entry)),
            }

            // If there were no unnotified entries, this one is the first now.
            if self.start.is_none() {
                self.start = self.tail;
            }

            // Bump the entry count.
            self.len += 1;
        }
    }

    /// Removes an entry from the list and returns its state.
    fn remove(&mut self, entry: NonNull<Entry>) -> State {
        unsafe {
            let prev = entry.as_ref().prev.get();
            let next = entry.as_ref().next.get();

            // Unlink from the previous entry.
            match prev {
                None => self.head = next,
                Some(p) => p.as_ref().next.set(next),
            }

            // Unlink from the next entry.
            match next {
                None => self.tail = prev,
                Some(n) => n.as_ref().prev.set(prev),
            }

            // If this was the first unnotified entry, move the pointer to the next one.
            if self.start == Some(entry) {
                self.start = next;
            }

            // Extract the state.
            let state = entry.as_ref().state.replace(State::Created);

            // Update the counters.
            if state.is_notified() {
                self.notified -= 1;
            }
            self.len -= 1;

            state
        }
    }

    /// Notifies a number of entries.
    #[cold]
    fn notify(&mut self, mut n: usize) {
        if n <= self.notified {
            return;
        }
        n -= self.notified;

        while n > 0 {
            n -= 1;

            // Notify the first unnotified entry.
            match self.start {
                None => break,
                Some(e) => {
                    // Get the entry and move the pointer forward.
                    let e = unsafe { e.as_ref() };
                    self.start = e.next.get();

                    // Set the state of this entry to `Notified` and notify.
                    match e.state.replace(State::Notified(false)) {
                        State::Notified(_) => {}
                        State::Created => {}
                        State::Polling(w) => w.wake(),
                    }

                    // Update the counter.
                    self.notified += 1;
                }
            }
        }
    }

    /// Notifies a number of additional entries.
    #[cold]
    fn notify_additional(&mut self, mut n: usize) {
        while n > 0 {
            n -= 1;

            // Notify the first unnotified entry.
            match self.start {
                None => break,
                Some(e) => {
                    // Get the entry and move the pointer forward.
                    let e = unsafe { e.as_ref() };
                    self.start = e.next.get();

                    // Set the state of this entry to `Notified` and notify.
                    match e.state.replace(State::Notified(true)) {
                        State::Notified(_) => {}
                        State::Created => {}
                        State::Polling(w) => w.wake(),
                    }

                    // Update the counter.
                    self.notified += 1;
                }
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use crate::sync::notify::Event;

    fn is_send<T: Send>() {}
    fn is_sync<T: Sync>() {}

    #[test]
    fn event_send_sync() {
        is_send::<Event>();
        is_sync::<Event>();
    }
}