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
use std::{
    sync::{
        atomic::{AtomicBool, Ordering},
        Arc,
    },
    task::Waker,
    thread::{self, Thread},
    time::{Duration, Instant},
};

#[derive(Debug, PartialEq)]
pub struct WaitTimeoutError;

impl std::error::Error for WaitTimeoutError {}

impl std::fmt::Display for WaitTimeoutError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str("timeout")
    }
}

#[derive(Debug)]
pub struct AsyncSignal {
    waker: Waker,
}

#[derive(Debug)]
struct SyncSignalInner {
    thread: Thread,
    notified: AtomicBool,
    park_called: AtomicBool,
}

#[derive(Debug)]
pub struct SyncSignal {
    inner: Arc<SyncSignalInner>,
}

#[derive(Debug)]
pub enum Signal {
    Async(AsyncSignal),
    Sync(SyncSignal),
}

impl From<Waker> for Signal {
    #[inline(always)]
    fn from(waker: Waker) -> Self {
        Self::Async(AsyncSignal { waker })
    }
}

impl From<AsyncSignal> for Signal {
    #[inline(always)]
    fn from(s: AsyncSignal) -> Self {
        Self::Async(s)
    }
}

impl SyncSignal {
    #[inline(always)]
    pub fn new() -> Self {
        SyncSignal {
            inner: Arc::new(SyncSignalInner {
                thread: thread::current(),
                notified: AtomicBool::new(false),
                park_called: AtomicBool::new(false),
            }),
        }
    }

    #[inline(always)]
    fn notified(&self) -> bool {
        self.inner.notified.load(Ordering::Acquire)
    }

    #[inline(always)]
    fn park(&self) {
        while !self.notified() {
            thread::park();
        }
    }

    #[inline(always)]
    fn park_timeout(&self, timeout: Duration) -> Result<(), WaitTimeoutError> {
        let start_time = Instant::now();
        let mut remaining = timeout;
        loop {
            thread::park_timeout(remaining);
            if self.notified() {
                return Ok(());
            }
            let elapsed = start_time.elapsed();
            if elapsed >= timeout {
                return Err(WaitTimeoutError);
            }
            remaining = timeout - elapsed;
        }
    }

    #[inline(always)]
    pub fn wait(&self) {
        if !self.inner.park_called.swap(true, Ordering::Relaxed) {
            self.park();
        }
    }

    #[inline(always)]
    pub fn wait_timeout(&self, timeout: Duration) -> Result<(), WaitTimeoutError> {
        if !self.inner.park_called.swap(true, Ordering::Relaxed) {
            return self.park_timeout(timeout);
        }
        Ok(())
    }

    #[inline(always)]
    pub fn notify(&self) {
        self.inner.notified.store(true, Ordering::Release);
        if self.inner.park_called.swap(true, Ordering::Relaxed) {
            self.inner.thread.unpark();
        }
    }
}

impl Clone for SyncSignal {
    #[inline(always)]
    fn clone(&self) -> Self {
        Self {
            inner: Arc::clone(&self.inner),
        }
    }
}

impl From<SyncSignal> for Signal {
    #[inline(always)]
    fn from(s: SyncSignal) -> Self {
        Self::Sync(s)
    }
}

impl Signal {
    #[inline(always)]
    pub fn wake(self) {
        match self {
            Self::Async(s) => s.waker.wake(),
            Self::Sync(s) => s.notify(),
        }
    }

    #[inline(always)]
    pub fn wake_by_ref(&self) {
        match self {
            Self::Async(s) => s.waker.wake_by_ref(),
            Self::Sync(s) => s.notify(),
        }
    }
}