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
#![doc = include_str!("../README.md")]

use std::{time, time::Duration, ops::Deref, sync::{Arc, Condvar, Mutex, MutexGuard}, mem};
use std::ops::DerefMut;

#[cfg(windows)]
pub mod windows;

// ------------------------------ DATA TYPES ----------------------------------
#[derive(Debug, PartialEq)]
pub enum WaitObjectError {
    /// OS error code with its description. This error code is only when using APIs based on OS.
    OsError(isize, String),

    /// Meaning a sync object gets broken (or poisoned) due to panic!()
    SynchronizationBroken,

    /// Wait is timed out
    Timeout
}

pub type Result<T> = std::result::Result<T, WaitObjectError>;

/// Create a wait event object of any type T. To use this wait object in multi-threaded scenario, just clone the object and distribute it.
///
/// This wait object is just a wrapper of Mutex and Condvar combination with the suggested pattern (from Rust document) for waiting a value.
///
/// There are two ways to wait. The first is just to want until an expected value.
///
/// ```rust, no_run
/// # use sync_wait_object::WaitEvent;
/// use std::thread;
/// let wait3 = WaitEvent::new_init(0);
/// let mut wait_handle = wait3.clone();
///
/// thread::spawn(move || {
///     for i in 1..=3 {
///         wait_handle.set_state(i).unwrap();
///     }
/// });
///
/// let timeout = std::time::Duration::from_secs(1);
/// let r#final = *wait3.wait(Some(timeout), |i| *i == 3).unwrap();
/// let current = *wait3.value().unwrap();
/// assert_eq!(r#final, 3);
/// assert_eq!(current, 3);
/// ```
///
/// The second is to wait and then reset the value to a desired state.
/// ```rust, no_run
/// # use sync_wait_object::WaitEvent;
/// use std::thread;
/// let wait3 = WaitEvent::new_init(0);
/// let mut wait_handle = wait3.clone();
///
/// thread::spawn(move || {
///     for i in 1..=3 {
///         wait_handle.set_state(i).unwrap();
///     }
/// });
///
/// let timeout = std::time::Duration::from_secs(1);
/// let r#final = wait3.wait_reset(Some(timeout), || 1, |i| *i == 3).unwrap();
/// let current = *wait3.value().unwrap();
/// assert_eq!(r#final, 3);
/// assert_eq!(current, 1);
/// ```
///
#[derive(Clone)]
pub struct WaitEvent<T>(Arc<(Mutex<T>, Condvar)>);

/// Wrapper of [`WaitEvent`] of type `bool`, which focuses on waiting for `true` without resetting.
#[derive(Clone)]
pub struct ManualResetEvent(WaitEvent<bool>);

/// Wrapper of [`WaitEvent`] of type `bool`, which focuses on waiting for `true` with automatic reset to `false`.
#[derive(Clone)]
pub struct AutoResetEvent(WaitEvent<bool>);

// Boolean signal with ability to wait and set state.
pub trait SignalWaitable {
    fn wait_until_set(&self) -> Result<bool>;
    fn wait(&self, timeout: Duration) -> Result<bool>;
    fn set(&mut self) -> Result<()>;
    fn reset(&mut self) -> Result<()>;
}

// ------------------------------ IMPLEMENTATIONS ------------------------------
impl<T> WaitEvent<T> {
    #[inline]
    pub fn new_init(initial_state: T) -> Self {
        Self(Arc::new((Mutex::new(initial_state), Condvar::new())))
    }

    pub fn value(&self) -> Result<MutexGuard<T>> {
        self.0.0.lock().map_err(|e| e.into())
    }

    /// Wait until the `checker` returns true, or timed-out from `timeout`.
    ///
    /// # Arguments
    ///
    /// * `timeout` - Maximum wait time
    /// * `checker` - Checker function, once it returns `true`, the wait ends
    pub fn wait(&self, timeout: Option<Duration>, checker: impl FnMut(&T) -> bool) -> Result<MutexGuard<T>> {
        match timeout {
            Some(_) => self.wait_with_waiter(timeout, checker),
            None => self.wait_with_waiter(timeout, checker)
        }
    }

    /// Wait until the `checker` returns true, or timed-out from `timeout`. If the wait ends from `checker` condition, the interval value is reset by `reset`.
    ///
    /// # Arguments
    ///
    /// * `timeout` - Maximum wait time
    /// * `reset` - Function that provides a reset value
    /// * `checker` - Checker function, once it returns `true`, the wait ends
    ///
    /// # Examples
    ///
    /// ```rust
    /// # use std::{thread, time::Duration};
    /// use sync_wait_object::{WaitEvent, WaitObjectError};
    ///
    /// let wait3 = WaitEvent::new_init(0);
    /// let mut wait_handle = wait3.clone();
    ///
    /// thread::spawn(move || {
    ///     for i in 1..=3 {
    ///         thread::sleep(Duration::from_millis(50));
    ///         wait_handle.set_state(i).unwrap();
    ///     }
    /// });
    ///
    /// let timeout = Duration::from_millis(250);
    /// let r#final = wait3.wait_reset(Some(timeout), || 0, |i| *i == 5);
    /// let current = *wait3.value().unwrap();
    /// assert_eq!(r#final, Err(WaitObjectError::Timeout));
    /// assert_eq!(current, 3);
    /// ```
    pub fn wait_reset(&self, timeout: Option<Duration>, reset: impl FnMut() -> T, checker: impl FnMut(&T) -> bool) -> Result<T> {
        match timeout {
            Some(_) => self.wait_and_reset_with_waiter(timeout, checker, reset),
            None => self.wait_and_reset_with_waiter(timeout, checker, reset)
        }
    }

    pub fn wait_with_waiter(&self, timeout: Option<Duration>, mut checker: impl FnMut(&T) -> bool) -> Result<MutexGuard<T>> {
        let (lock, cond) = self.0.deref();
        let mut state = lock.lock()?;
        let waiter = Self::create_waiter(timeout);
        let mut continue_wait = waiter();
        let mut pass = checker(&*state);
        while continue_wait && !pass {
            state = match timeout {
                Some(t) => {
                    let (g, _) = cond.wait_timeout(state, t)?;
                    g
                },
                None => cond.wait(state)?
            };
            continue_wait = waiter();
            pass = checker(&*state);
        }
        if pass { Ok(state) }
        else { Err(WaitObjectError::Timeout) }
    }

    pub fn wait_and_reset_with_waiter(&self, timeout: Option<Duration>, checker: impl FnMut(&T) -> bool, mut reset: impl FnMut() -> T) -> Result<T> {
        let state = self.wait_with_waiter(timeout, checker);
        state.map(|mut g| mem::replace(g.deref_mut(), reset()))
    }

    fn create_waiter(timeout: Option<Duration>) -> impl Fn() -> bool {
        let start = time::Instant::now();
        move || {
            match timeout {
                Some(t) => (time::Instant::now() - start) < t,
                None => true
            }
        }
    }

    pub fn set_state(&mut self, new_state: T) -> Result<()> {
        let (lock, cond) = self.0.deref();
        let mut state = lock.lock()?;
        *state = new_state;
        cond.notify_all();
        Ok(())
    }
}

impl ManualResetEvent {
    #[inline]
    pub fn new() -> Self { Self::new_init(false) }

    #[inline]
    pub fn new_init(initial_state: bool) -> Self {
        Self(WaitEvent::new_init(initial_state))
    }
}

impl SignalWaitable for ManualResetEvent {
    #[inline]
    fn wait_until_set(&self) -> Result<bool> {
        self.0.wait(None, |v| *v).map(|g| *g)
    }

    #[inline] fn wait(&self, timeout: Duration) -> Result<bool> {
        self.0.wait(Some(timeout), |v| *v).map(|g| *g)
    }

    #[inline]
    fn set(&mut self) -> Result<()> {
        self.0.set_state(true)
    }

    #[inline]
    fn reset(&mut self) -> Result<()> {
        self.0.set_state(false)
    }
}

impl AutoResetEvent {
    #[inline]
    pub fn new() -> Self { Self::new_init(false) }

    #[inline]
    pub fn new_init(initial_state: bool) -> Self {
        Self(WaitEvent::new_init(initial_state))
    }
}

impl SignalWaitable for AutoResetEvent {
    #[inline]
    fn wait_until_set(&self) -> Result<bool> {
        self.0.wait_reset(None, || false, |v| *v)
    }

    #[inline] fn wait(&self, timeout: Duration) -> Result<bool> {
        self.0.wait_reset(Some(timeout), || false, |v| *v)
    }

    #[inline]
    fn set(&mut self) -> Result<()> {
        self.0.set_state(true)
    }

    #[inline]
    fn reset(&mut self) -> Result<()> {
        self.0.set_state(false)
    }
}

impl<T> From<std::sync::PoisonError<T>> for WaitObjectError {
    fn from(_value: std::sync::PoisonError<T>) -> Self {
        Self::SynchronizationBroken
    }
}

impl From<WaitEvent<bool>> for ManualResetEvent {
    fn from(value: WaitEvent<bool>) -> Self {
                                          Self(value)
                                                     }
}

impl From<ManualResetEvent> for WaitEvent<bool> {
    fn from(value: ManualResetEvent) -> Self {
                                           value.0
                                                  }
}

impl From<WaitEvent<bool>> for AutoResetEvent {
    fn from(value: WaitEvent<bool>) -> Self {
                                          Self(value)
                                                     }
}

impl From<AutoResetEvent> for WaitEvent<bool> {
    fn from(value: AutoResetEvent) -> Self {
                                         value.0
                                                }
}