forked from Volkalex28/channel-bridge
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnotification.rs
53 lines (43 loc) · 1.15 KB
/
notification.rs
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
use core::future::{poll_fn, Future};
use core::sync::atomic::{AtomicBool, Ordering};
use core::task::{Context, Poll};
use atomic_waker::AtomicWaker;
pub struct Notification {
waker: AtomicWaker,
triggered: AtomicBool,
}
impl Notification {
pub const fn new() -> Self {
Self {
waker: AtomicWaker::new(),
triggered: AtomicBool::new(false),
}
}
pub fn reset(&self) {
self.triggered.store(false, Ordering::SeqCst);
self.waker.take();
}
pub fn notify(&self) {
self.triggered.store(true, Ordering::SeqCst);
self.waker.wake();
}
pub fn triggered(&self) -> bool {
self.triggered.load(Ordering::SeqCst)
}
pub fn wait(&self) -> impl Future<Output = ()> + '_ {
poll_fn(move |cx| self.poll_wait(cx))
}
pub fn poll_wait(&self, cx: &mut Context<'_>) -> Poll<()> {
self.waker.register(cx.waker());
if self.triggered.swap(false, Ordering::SeqCst) {
Poll::Ready(())
} else {
Poll::Pending
}
}
}
impl Default for Notification {
fn default() -> Self {
Self::new()
}
}