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
// SPDX-License-Identifier: LGPL-3.0-or-later OR MPL-2.0
// This file is a part of `unsend`.
//
// `unsend` is free software: you can redistribute it and/or modify it under the
// terms of either:
//
// * GNU Lesser General Public License as published by the Free Software Foundation, either
//   version 3 of the License, or (at your option) any later version.
// * Mozilla Public License as published by the Mozilla Foundation, version 2.
// * The Patron License (https://github.com/notgull/unsend/blob/main/LICENSE-PATRON.md)
//   for sponsors and contributors, who can ignore the copyleft provisions of the above licenses
//   for this project.
//
// `unsend` is distributed in the hope that it will be useful, but WITHOUT ANY
// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
// PURPOSE. See the GNU Lesser General Public License or the Mozilla Public License for more
// details.
//
// You should have received a copy of the GNU Lesser General Public License and the Mozilla
// Public License along with `unsend`. If not, see <https://www.gnu.org/licenses/>.

//! Asynchronous locking primitives.

mod barrier;
mod mutex;
mod once_cell;
mod rwlock;
mod semaphore;

pub use barrier::{Barrier, BarrierWaitResult};
pub use mutex::{Mutex, MutexGuard};
pub use once_cell::OnceCell;
pub use rwlock::{RwLock, RwLockReadGuard, RwLockWriteGuard};
pub use semaphore::{Semaphore, SemaphoreGuard};

#[cfg(feature = "alloc")]
pub use semaphore::SemaphoreGuardRc;

#[cfg(test)]
mod tests {
    use super::*;
    use futures_lite::future;

    #[test]
    fn test_mutex() {
        future::block_on(async {
            let mutex = Mutex::new(0);
            let mut guard = mutex.lock().await;
            *guard += 1;
            assert_eq!(*guard, 1);
            drop(guard);
            let guard = mutex.lock().await;

            // If we try to lock the mutex again, it will block.
            assert!(mutex.try_lock().is_none());
            assert!(future::poll_once(mutex.lock()).await.is_none());

            assert_eq!(*guard, 1);
        });
    }

    #[test]
    fn test_mutex_try_lock() {
        future::block_on(async {
            let mutex = Mutex::new(0);
            let mut guard = mutex.try_lock().unwrap();
            *guard += 1;
            assert_eq!(*guard, 1);
            drop(guard);
            let guard = mutex.try_lock().unwrap();
            assert_eq!(*guard, 1);
        });
    }

    #[test]
    fn test_mutex_try_lock_fail() {
        future::block_on(async {
            let mutex = Mutex::new(0);
            let mut guard = mutex.lock().await;
            *guard += 1;
            assert_eq!(*guard, 1);
            drop(guard);
            let guard = mutex.lock().await;
            assert_eq!(*guard, 1);
        });
    }

    #[test]
    fn test_mutex_lock_after_drop() {
        future::block_on(async {
            let mutex = Mutex::new(0);
            let mut guard = mutex.lock().await;
            *guard += 1;
            assert_eq!(*guard, 1);
            drop(guard);
            let guard = mutex.lock().await;
            assert_eq!(*guard, 1);
        });
    }

    #[test]
    fn test_mutex_lock_after_drop_try_lock() {
        future::block_on(async {
            let mutex = Mutex::new(0);
            let mut guard = mutex.try_lock().unwrap();
            *guard += 1;
            assert_eq!(*guard, 1);
            drop(guard);
            let guard = mutex.try_lock().unwrap();
            assert_eq!(*guard, 1);
        });
    }

    #[test]
    fn test_mutex_get_mut_into_inner() {
        let mut mutex = Mutex::<i32>::default();
        *mutex.get_mut() = 3;
        assert_eq!(mutex.into_inner(), 3);
    }

    #[test]
    fn test_mutex_lock_await() {
        future::block_on(async {
            let mutex = Mutex::new(0);
            let mut guard = mutex.lock().await;
            *guard += 1;

            let lock2 = mutex.lock();
            futures_lite::pin!(lock2);

            assert!(future::poll_once(&mut lock2).await.is_none());
            drop(guard);
            assert!(future::poll_once(&mut lock2).await.is_some());
        });
    }

    #[test]
    fn test_rwlock() {
        future::block_on(async {
            let rwlock = RwLock::new(0);
            let mut guard = rwlock.write().await;
            *guard += 1;
            assert_eq!(*guard, 1);
            drop(guard);
            let guard = rwlock.read().await;
            assert_eq!(*guard, 1);
            drop(guard);
            let guard = rwlock.write().await;
            assert_eq!(*guard, 1);
        });
    }

    #[test]
    fn test_rwlock_try_read() {
        future::block_on(async {
            let rwlock = RwLock::new(0);
            let mut guard = rwlock.write().await;
            *guard += 1;
            assert_eq!(*guard, 1);
            drop(guard);
            let guard = rwlock.try_read().unwrap();
            assert_eq!(*guard, 1);
            drop(guard);
            let guard = rwlock.write().await;
            assert_eq!(*guard, 1);
        });
    }

    #[test]
    fn test_rwlock_try_write() {
        future::block_on(async {
            let rwlock = RwLock::new(0);
            let mut guard = rwlock.write().await;
            *guard += 1;
            assert_eq!(*guard, 1);
            drop(guard);
            let guard = rwlock.read().await;
            assert_eq!(*guard, 1);
            drop(guard);
            let guard = rwlock.try_write().unwrap();
            assert_eq!(*guard, 1);
        });
    }

    #[test]
    fn test_rwlock_get_mut() {
        let mut rwlock = RwLock::<i32>::default();
        *rwlock.get_mut() = 3;
        assert_eq!(rwlock.into_inner(), 3);
    }

    #[test]
    fn test_rwlock_read_write_await() {
        future::block_on(async {
            let rwlock = RwLock::new(0);
            let guard = rwlock.write().await;
            assert_eq!(*guard, 0);

            let read2 = rwlock.read();
            futures_lite::pin!(read2);

            assert!(future::poll_once(&mut read2).await.is_none());
            drop(guard);
            assert!(future::poll_once(&mut read2).await.is_some());

            let guard = rwlock.read().await;
            assert_eq!(*guard, 0);

            let write2 = rwlock.write();
            futures_lite::pin!(write2);

            assert!(future::poll_once(&mut write2).await.is_none());
            drop(guard);
            assert!(future::poll_once(&mut write2).await.is_some());
        });
    }

    #[test]
    fn test_semaphore() {
        future::block_on(async {
            let semaphore = Semaphore::new(1);
            let _guard = semaphore.acquire().await;

            // If we try to acquire the semaphore again, it will block.
            assert!(semaphore.try_acquire().is_none());
            assert!(future::poll_once(semaphore.acquire()).await.is_none());
        });
    }

    #[test]
    fn test_semaphore_await() {
        future::block_on(async {
            let semaphore = Semaphore::new(1);
            let _guard = semaphore.acquire().await;

            // If we try to acquire the semaphore again, it will block.
            assert!(semaphore.try_acquire().is_none());

            let acquire = semaphore.acquire();
            futures_lite::pin!(acquire);

            assert!(future::poll_once(&mut acquire).await.is_none());
            drop(_guard);
            assert!(future::poll_once(&mut acquire).await.is_some());
        });
    }

    #[cfg(feature = "alloc")]
    #[test]
    fn test_semaphore_rc() {
        use alloc::rc::Rc;

        future::block_on(async {
            let semaphore = Rc::new(Semaphore::new(1));
            let _guard = semaphore.clone().acquire_rc().await;

            // If we try to acquire the semaphore again, it will block.
            assert!(semaphore.clone().try_acquire_rc().is_none());
            assert!(future::poll_once(semaphore.acquire()).await.is_none());
        });
    }

    #[cfg(feature = "alloc")]
    #[test]
    fn test_semaphore_rc_await() {
        use alloc::rc::Rc;

        future::block_on(async {
            let semaphore = Rc::new(Semaphore::new(1));
            let _guard = semaphore.clone().acquire_rc().await;

            // If we try to acquire the semaphore again, it will block.
            assert!(semaphore.clone().try_acquire_rc().is_none());

            let acquire = semaphore.acquire_rc();
            futures_lite::pin!(acquire);

            assert!(future::poll_once(&mut acquire).await.is_none());
            drop(_guard);
            assert!(future::poll_once(&mut acquire).await.is_some());
        });
    }

    #[test]
    fn once_cell_smoke() {
        future::block_on(async {
            let cell = OnceCell::<i32>::new();
            assert!(cell.get().is_none());

            let value = cell.get_or_init(async { 5 }).await;
            assert_eq!(*value, 5);
            assert_eq!(cell.get().unwrap(), &5);
        });
    }

    #[test]
    fn once_cell_get_mut() {
        let mut cell = OnceCell::<i32>::from(5);
        assert!(cell.get_mut().is_some());
        assert_eq!(cell.take(), Some(5));
    }

    #[test]
    fn once_cell_wait() {
        future::block_on(async {
            let cell = OnceCell::<i32>::new();

            let waiter = cell.wait();
            futures_lite::pin!(waiter);

            assert!(future::poll_once(&mut waiter).await.is_none());
            cell.set(5).await.unwrap();
            assert!(future::poll_once(&mut waiter).await.is_some());
        });
    }

    #[test]
    fn once_cell_set2() {
        future::block_on(async {
            let cell = OnceCell::<i32>::from(3);
            assert_eq!(cell.set(5).await, Err(5));
        });
    }

    #[cfg(feature = "alloc")]
    #[test]
    fn barrier_smoke() {
        future::block_on(async {
            let barrier = Barrier::new(2);

            // Start two tasks that wait on the barrier.
            let wait1 = barrier.wait();
            futures_lite::pin!(wait1);

            assert!(future::poll_once(wait1.as_mut()).await.is_none());

            // Wait on the barrier in the current task.
            let result = barrier.wait().await;
            assert!(result.clone().is_leader());

            // Eat coverage for debug.
            alloc::format!("{:?}", result);

            // The other tasks should now be unblocked.
            let result = future::poll_once(wait1.as_mut()).await.unwrap();
            assert!(!result.is_leader());
        });
    }
}