Skip to main content

kithara_platform/sync/
condvar.rs

1#[cfg(not(target_arch = "wasm32"))]
2use parking_lot::Condvar as ParkingLotCondvar;
3
4use super::MutexGuard;
5
6#[cfg(not(target_arch = "wasm32"))]
7pub struct Condvar(ParkingLotCondvar);
8
9#[cfg(not(target_arch = "wasm32"))]
10impl Condvar {
11    #[inline]
12    #[must_use]
13    pub fn new() -> Self {
14        Self(ParkingLotCondvar::new())
15    }
16
17    #[inline]
18    pub fn notify_all(&self) {
19        self.0.notify_all();
20    }
21
22    #[inline]
23    pub fn notify_one(&self) {
24        self.0.notify_one();
25    }
26
27    #[inline]
28    pub fn wait_sync<'a, T>(&self, mut guard: MutexGuard<'a, T>) -> MutexGuard<'a, T> {
29        self.0.wait(&mut guard.0);
30        guard
31    }
32
33    #[inline]
34    pub fn wait_sync_timeout<'a, T>(
35        &self,
36        mut guard: MutexGuard<'a, T>,
37        deadline: web_time::Instant,
38    ) -> (MutexGuard<'a, T>, WaitTimeoutResult) {
39        let result = self.0.wait_until(&mut guard.0, deadline);
40        (guard, WaitTimeoutResult(result.timed_out()))
41    }
42}
43
44#[cfg(not(target_arch = "wasm32"))]
45impl Default for Condvar {
46    fn default() -> Self {
47        Self::new()
48    }
49}
50
51#[cfg(target_arch = "wasm32")]
52type WstCondvar = wasm_safe_thread::condvar::Condvar;
53
54#[cfg(target_arch = "wasm32")]
55pub struct Condvar(WstCondvar);
56
57#[cfg(target_arch = "wasm32")]
58impl Condvar {
59    #[inline]
60    #[must_use]
61    pub fn new() -> Self {
62        Self(WstCondvar::new())
63    }
64
65    #[inline]
66    pub fn notify_all(&self) {
67        self.0.notify_all();
68    }
69
70    #[inline]
71    pub fn notify_one(&self) {
72        self.0.notify_one();
73    }
74
75    #[inline]
76    pub fn wait_sync<'a, T>(&self, guard: MutexGuard<'a, T>) -> MutexGuard<'a, T> {
77        MutexGuard(self.0.wait_sync(guard.0))
78    }
79
80    #[inline]
81    pub fn wait_sync_timeout<'a, T>(
82        &self,
83        guard: MutexGuard<'a, T>,
84        deadline: web_time::Instant,
85    ) -> (MutexGuard<'a, T>, WaitTimeoutResult) {
86        let (g, result) = self.0.wait_sync_timeout(guard.0, deadline);
87        (MutexGuard(g), WaitTimeoutResult(result.timed_out()))
88    }
89}
90
91#[cfg(target_arch = "wasm32")]
92impl Default for Condvar {
93    fn default() -> Self {
94        Self::new()
95    }
96}
97
98/// Result of a timed wait on a [`Condvar`].
99#[derive(Debug, Clone, Copy, PartialEq, Eq)]
100pub struct WaitTimeoutResult(bool);
101
102impl WaitTimeoutResult {
103    /// Returns `true` if the wait timed out (deadline elapsed).
104    #[inline]
105    #[must_use]
106    pub fn did_time_out(&self) -> bool {
107        self.0
108    }
109}