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
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
//! Generic mutex that only needs lock and unlock functionality to be auto
//! implemented.

#[cfg(feature = "alloc")]
mod mutex_alloc;

#[cfg(feature = "std")]
mod mutex_std;

#[cfg(feature = "impl_parking_lot")]
mod mutex_parking_lot;

#[cfg(feature = "alloc")]
pub use mutex_alloc::*;

use crate::{EnsureSend, EnsureSync};

use core::cell::UnsafeCell;
use core::future::Future;
use core::ops::{Deref, DerefMut};
use core::time::Duration;

/// A non-blocking mutex with try functions.
///
/// ## Implementation
/// It is recommended to implement [`TryMutexSized`] if the implement-ee can be
/// sized.
pub trait TryMutex<'a> {
    /// The item stored in the mutex
    type Item: ?Sized;
    /// The guard for the mutex
    type Guard: DerefMut<Target = Self::Item>;

    /// Tries to lock the mutex, returning `None` if not possible.
    fn try_lock(&'a self) -> Option<Self::Guard>;
}
/// The functions for [`TryMutex`] that only work for sized types.
/// Separated to allow [`TryMutex`] to be a trait object.
pub trait TryMutexSized<'a>: Sized + TryMutex<'a> {
    /// Runs the function the value in the mutex if available immediately.
    ///
    /// ## Implementation
    /// Should be overwritten by implementors if can be more optimal than
    /// creating a guard
    fn try_lock_func<O>(&'a self, func: impl FnOnce(Option<&mut Self::Item>) -> O) -> O {
        match self.try_lock() {
            None => func(None),
            Some(mut guard) => func(Some(guard.deref_mut())),
        }
    }
}
/// A Generic Mutex trait
///
/// ## Implementation
/// It is recommended to implement [`MutexSized`] if the implement-ee can be
/// sized.
pub trait Mutex<'a>: TryMutex<'a> {
    /// Locks the mutex, blocking until successful
    fn lock(&'a self) -> Self::Guard;
}
/// The functions for [`Mutex`] that only work for sized types.
/// Separated to allow [`Mutex`] to be a trait object.
pub trait MutexSized<'a>: Mutex<'a> + TryMutexSized<'a> {
    /// Runs the function on the value in the mutex.
    ///
    /// ## Implementation
    /// Should be overwritten by implementors if can be more optimal than
    /// creating a guard
    fn lock_func<O>(&'a self, func: impl FnOnce(&mut Self::Item) -> O) -> O {
        func(self.lock().deref_mut())
    }
}
/// A generic async mutex trait
///
/// ## Implementation
/// It is recommended to implement [`AsyncMutexSized`] if the implement-ee can
/// be sized.
pub trait AsyncMutex<'a>: TryMutex<'a> {
    /// The guard for this async mutex
    type AsyncGuard: DerefMut<Target = Self::Item>;
    /// The future that the [`AsyncMutex::lock_async`] function returns
    type LockFuture: Future<Output = Self::AsyncGuard>;

    /// Locks the mutex asynchronously, returning a future with the guard.
    fn lock_async(&'a self) -> Self::LockFuture;
}

/// A mutex that can timeout for locking
///
/// ## Implementation
/// It is recommended to implement [`TimeoutMutexSized`] if the implement-ee can
/// be sized.
pub trait TimeoutMutex<'a>: TryMutex<'a> {
    /// Locks the mutex blocking for timeout or until locked
    fn lock_timeout(&'a self, timeout: Duration) -> Option<Self::Guard>;
}
/// The functions for [`TimeoutMutex`] that only work for sized types.
/// Separated to allow [`TimeoutMutex`] to be a trait object.
pub trait TimeoutMutexSized<'a>: Sized + TimeoutMutex<'a> + TryMutexSized<'a> {
    /// Attempts to lock the mutex before timeout has passed and runs func on
    /// the result
    ///
    /// ## Implementation
    /// Should be overwritten by implementors if can be more optimal than
    /// creating a guard
    fn lock_timeout_func<O>(
        &'a self,
        timeout: Duration,
        func: impl FnOnce(Option<&mut Self::Item>) -> O,
    ) -> O {
        match self.lock_timeout(timeout) {
            None => func(None),
            Some(mut guard) => func(Some(guard.deref_mut())),
        }
    }
}
/// An async mutex that locking can timeout on.
///
/// ## Implementation
/// It is recommended to implement [`AsyncTimeoutMutexSized`] if the
/// implement-ee can be sized.
pub trait AsyncTimeoutMutex<'a>: AsyncMutex<'a> {
    /// The future returned by `lock_timeout_async`
    type LockTimeoutFuture: Future<Output = Option<Self::AsyncGuard>>;
    /// Locks the mutex asynchronously with a timeout.
    fn lock_timeout_async(&'a self, timeout: Duration) -> Self::LockTimeoutFuture;
}

/// A raw mutex that can be tried and holds no data.
pub trait RawTryMutex {
    /// Locks the mutex, non-blocking. Returns true if locked.
    fn try_lock(&self) -> bool;
    /// # Safety
    /// Must only be called when sure that no references exist to contained
    /// data.
    unsafe fn unlock(&self);
}
/// A raw mutex that hold no data but the lock itself.
pub trait RawMutex: RawTryMutex {
    /// Locks the mutex, blocking.
    fn lock(&self);
}
/// A raw async mutex that hold no data but the lock itself.
pub trait RawAsyncMutex: RawTryMutex {
    /// The future returned by [`RawAsyncMutex::lock_async`]
    type LockFuture: Future<Output = ()>;
    /// Locks the mutex asynchronously
    fn lock_async(&self) -> Self::LockFuture;
}
/// A raw mutex that can be timed out and holds no data.
pub trait RawTimeoutMutex: RawMutex {
    /// Locks the mutex on a timeout. Returns true if locked.
    fn lock_timeout(&self, timeout: Duration) -> bool;
}
/// A raw async mutex that can be timed out and holds no data.
pub trait RawAsyncTimeoutMutex: RawAsyncMutex {
    /// The future returned by [`RawAsyncTimeoutMutex::lock_timeout_async`]
    type LockTimeoutFuture: Future<Output = bool>;
    /// Locks the mutex on a timeout asynchronously. Returns true if locked.
    fn lock_timeout_async(&self, timeout: Duration) -> Self::LockTimeoutFuture;
}

/// A Mutex based on a given [`RawTryMutex`]
#[derive(Debug)]
pub struct CustomMutex<T, M: ?Sized> {
    data: UnsafeCell<T>,
    raw_mutex: M,
}
impl<T, M> CustomMutex<T, M> {
    /// Creates a new `CustomMutex` with a `RawMutex`
    pub const fn from_raw(raw_mutex: M, data: T) -> Self {
        Self {
            raw_mutex,
            data: UnsafeCell::new(data),
        }
    }

    /// Creates a new mutex with a default raw
    pub fn new(data: T) -> Self
    where
        M: Default,
    {
        Self::from_raw(M::default(), data)
    }
}
impl<'a, T, M> TryMutex<'a> for CustomMutex<T, M>
where
    T: 'a,
    M: RawTryMutex + 'a,
{
    type Item = T;
    type Guard = CustomMutexGuard<'a, T, M>;

    fn try_lock(&'a self) -> Option<Self::Guard> {
        match self.raw_mutex.try_lock() {
            true => Some(CustomMutexGuard { mutex: self }),
            false => None,
        }
    }
}
impl<'a, T, M> TryMutexSized<'a> for CustomMutex<T, M>
where
    T: 'a,
    M: RawTryMutex + 'a,
{
    fn try_lock_func<O>(&'a self, func: impl FnOnce(Option<&mut Self::Item>) -> O) -> O {
        match self.raw_mutex.try_lock() {
            true => unsafe {
                let out = func(Some(&mut *self.data.get()));
                self.raw_mutex.unlock();
                out
            },
            false => func(None),
        }
    }
}
impl<'a, T, M> Mutex<'a> for CustomMutex<T, M>
where
    T: 'a,
    M: RawMutex + 'a,
{
    fn lock(&'a self) -> Self::Guard {
        self.raw_mutex.lock();
        CustomMutexGuard { mutex: self }
    }
}

impl<'a, T, M> MutexSized<'a> for CustomMutex<T, M>
where
    T: 'a,
    M: RawMutex + 'a,
{
    fn lock_func<O>(&'a self, func: impl FnOnce(&mut Self::Item) -> O) -> O {
        self.raw_mutex.lock();
        let out = func(unsafe { &mut *self.data.get() });
        unsafe { self.raw_mutex.unlock() }
        out
    }
}
impl<'a, T, M> TimeoutMutex<'a> for CustomMutex<T, M>
where
    T: 'a,
    M: RawTimeoutMutex + 'a,
{
    fn lock_timeout(&'a self, timeout: Duration) -> Option<Self::Guard> {
        match self.raw_mutex.lock_timeout(timeout) {
            true => Some(CustomMutexGuard { mutex: self }),
            false => None,
        }
    }
}
impl<'a, T, M> TimeoutMutexSized<'a> for CustomMutex<T, M>
where
    T: 'a,
    M: RawTimeoutMutex + 'a,
{
    fn lock_timeout_func<O>(
        &'a self,
        timeout: Duration,
        func: impl FnOnce(Option<&mut Self::Item>) -> O,
    ) -> O {
        match self.raw_mutex.lock_timeout(timeout) {
            true => unsafe {
                let out = func(Some(&mut *self.data.get()));
                self.raw_mutex.unlock();
                out
            },
            false => func(None),
        }
    }
}
impl<T, M> Default for CustomMutex<T, M>
where
    T: Default,
    M: Default,
{
    #[inline]
    fn default() -> Self {
        Self::new(T::default())
    }
}
impl<T, M> From<T> for CustomMutex<T, M>
where
    M: Default,
{
    fn from(from: T) -> Self {
        Self::new(from)
    }
}
impl<T, M> EnsureSend for CustomMutex<T, M>
where
    T: Send,
    M: Send,
{
}
unsafe impl<T, M> Sync for CustomMutex<T, M>
where
    T: Send,
    M: Sync,
{
}

/// A guard for a `CustomMutex`
#[derive(Debug)]
pub struct CustomMutexGuard<'a, T, M>
where
    M: RawTryMutex,
{
    mutex: &'a CustomMutex<T, M>,
}
impl<'a, T, M> Deref for CustomMutexGuard<'a, T, M>
where
    M: RawTryMutex,
{
    type Target = T;

    fn deref(&self) -> &Self::Target {
        unsafe { &*self.mutex.data.get() }
    }
}
impl<'a, T, M> DerefMut for CustomMutexGuard<'a, T, M>
where
    M: RawTryMutex,
{
    fn deref_mut(&mut self) -> &mut Self::Target {
        unsafe { &mut *self.mutex.data.get() }
    }
}
impl<'a, T, M> Drop for CustomMutexGuard<'a, T, M>
where
    M: RawTryMutex,
{
    fn drop(&mut self) {
        unsafe { self.mutex.raw_mutex.unlock() }
    }
}
impl<'a, T, M> EnsureSend for CustomMutexGuard<'a, T, M>
where
    T: Send,
    M: RawTryMutex + Send + Sync,
{
}
impl<'a, T, M> EnsureSync for CustomMutexGuard<'a, T, M>
where
    T: Send,
    M: RawTryMutex + Send + Sync,
{
}

#[cfg(test)]
mod test {
    use crate::mutex::{
        CustomMutex, Mutex, MutexSized, RawMutex, RawTryMutex, TryMutex, TryMutexSized,
    };
    use std::mem::swap;
    use std::ops::{Deref, DerefMut};
    use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
    use std::sync::{self, Arc, Condvar};
    use std::thread::{spawn, yield_now};

    // True if unlocked
    struct AtomicTryMutex {
        unlocked: AtomicBool,
    }
    impl Default for AtomicTryMutex {
        fn default() -> Self {
            Self {
                unlocked: AtomicBool::new(true),
            }
        }
    }
    impl RawTryMutex for AtomicTryMutex {
        fn try_lock(&self) -> bool {
            self.unlocked.swap(false, Ordering::SeqCst)
        }

        unsafe fn unlock(&self) {
            assert!(!self.unlocked.swap(true, Ordering::SeqCst));
        }
    }
    #[test]
    fn try_mutex_test() {
        let custom_mutex: CustomMutex<_, AtomicTryMutex> = CustomMutex::new(100);
        assert_eq!(
            custom_mutex.try_lock().map(|guard| *guard.deref()),
            Some(100)
        );
        let mut guard = custom_mutex.try_lock().expect("Could not lock!");
        *guard.deref_mut() = 200;
        drop(guard);
        custom_mutex.try_lock_func(|guard| {
            let value = guard.expect("Could not lock");
            assert_eq!(*value, 200);
            *value = 300;
        });
        let guard = custom_mutex.try_lock().expect("Could not lock!");
        assert!(custom_mutex.try_lock().is_none());
        assert_eq!(*guard, 300);
    }

    struct TestMutex {
        unlocked: sync::Mutex<bool>,
        parkers: Condvar,
    }
    impl Default for TestMutex {
        fn default() -> Self {
            Self {
                unlocked: sync::Mutex::new(true),
                parkers: Condvar::new(),
            }
        }
    }
    impl RawTryMutex for TestMutex {
        fn try_lock(&self) -> bool {
            let mut out = false;
            swap(
                self.unlocked.lock().expect("Poisoned").deref_mut(),
                &mut out,
            );
            out
        }

        unsafe fn unlock(&self) {
            let mut out = true;
            swap(
                self.unlocked.lock().expect("Poisoned").deref_mut(),
                &mut out,
            );
            assert!(!out);
            self.parkers.notify_one();
        }
    }
    impl RawMutex for TestMutex {
        fn lock(&self) {
            let mut guard = self.unlocked.lock().expect("Poisoned");
            let mut out = false;
            swap(guard.deref_mut(), &mut out);
            if !out {
                drop(
                    self.parkers
                        .wait_while(guard, |val| {
                            let mut out = false;
                            swap(val, &mut out);
                            !out
                        })
                        .expect("Poisoned"),
                );
            }
        }
    }
    #[test]
    fn mutex_test() {
        let custom_mutex: CustomMutex<_, TestMutex> = CustomMutex::new(100);
        assert_eq!(
            custom_mutex.try_lock().map(|guard| *guard.deref()),
            Some(100)
        );
        let mut guard = custom_mutex.try_lock().expect("Could not lock!");
        *guard.deref_mut() = 200;
        drop(guard);
        custom_mutex.try_lock_func(|guard| {
            let value = guard.expect("Could not lock");
            assert_eq!(*value, 200);
            *value = 300;
        });
        let guard = custom_mutex.try_lock().expect("Could not lock!");
        assert!(custom_mutex.try_lock().is_none());
        assert_eq!(*guard, 300);
        drop(guard);
        assert_eq!(*custom_mutex.lock(), 300);
        let arc = Arc::new((custom_mutex, AtomicUsize::new(0)));
        let arc_clone = arc.clone();
        let guard = arc.0.lock();
        let handle = spawn(move || {
            arc_clone.0.lock_func(|val| {
                assert_eq!(*val, 300);
                *val = 400;
            });
            arc_clone.1.fetch_add(1, Ordering::SeqCst);
        });
        yield_now();
        assert_eq!(arc.1.load(Ordering::SeqCst), 0);
        drop(guard);
        handle.join().expect("Could not join");
        assert_eq!(arc.1.load(Ordering::SeqCst), 1);
        assert_eq!(*arc.0.lock(), 400);
    }
}