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
//! Provides a simple mutex that does not support blocking or poisoning, but is
//! faster and simpler than the mutex in stdlib.

use std::cell::UnsafeCell;
use std::convert::From;
use std::fmt;
use std::fmt::{Debug, Display};
use std::marker::PhantomData;
use std::ops::{Deref, DerefMut};
use std::panic::{RefUnwindSafe, UnwindSafe};
use std::sync::atomic::{AtomicBool, Ordering};

/// A mutual exclusion primitive that does not support blocking or poisoning.
/// This results in a simpler and faster implementation.
pub struct TryMutex<T> {
    data: UnsafeCell<T>,
    locked: AtomicBool,
}

impl<T> TryMutex<T> {
    /// Create a new mutex in unlocked state.
    #[inline]
    pub const fn new(t: T) -> Self {
        TryMutex {
            data: UnsafeCell::new(t),
            locked: AtomicBool::new(false),
        }
    }

    /// Attemps to acquire a lock on this mutex. If this mutex is currently
    /// locked, `None` is returned. Otherwise a RAII guard is returned. The lock
    /// will be unlocked when the guard is dropped.
    #[inline]
    pub fn try_lock(&self) -> Option<TryMutexGuard<T>> {
        if self.locked.compare_and_swap(false, true, Ordering::Acquire) {
            None
        } else {
            Some(TryMutexGuard {
                lock: self,
                notsend: PhantomData,
            })
        }
    }

    /// Consumes this mutex, returning the underlying data.
    #[inline]
    pub fn into_inner(self) -> T {
        self.data.into_inner()
    }

    /// Retrieve a mutable reference to the underlying data. Since this mutably
    /// borrows the mutex, no actual locking needs to take place.
    #[inline]
    pub fn get_mut(&mut self) -> &mut T {
        unsafe { &mut *self.data.get() }
    }
}

impl<T: Default> Default for TryMutex<T> {
    fn default() -> Self {
        Self::new(T::default())
    }
}

impl<T: Debug> Debug for TryMutex<T> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        if let Some(guard) = self.try_lock() {
            f.debug_struct("TryMutex").field("data", &*guard).finish()
        } else {
            struct LockedPlaceholder;
            impl fmt::Debug for LockedPlaceholder {
                fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
                    f.write_str("<locked>")
                }
            }

            f.debug_struct("TryMutex")
                .field("data", &LockedPlaceholder)
                .finish()
        }
    }
}

/// A RAII scoped lock on a `TryMutex`. When this this structure is dropped, the
/// mutex will be unlocked.
pub struct TryMutexGuard<'a, T: 'a> {
    lock: &'a TryMutex<T>,
    notsend: PhantomData<*mut T>,
}

impl<'a, T> Deref for TryMutexGuard<'a, T> {
    type Target = T;

    fn deref(&self) -> &T {
        unsafe { &*self.lock.data.get() }
    }
}

impl<'a, T> DerefMut for TryMutexGuard<'a, T> {
    fn deref_mut(&mut self) -> &mut T {
        unsafe { &mut *self.lock.data.get() }
    }
}

impl<'a, T> Drop for TryMutexGuard<'a, T> {
    fn drop(&mut self) {
        self.lock.locked.store(false, Ordering::Release);
    }
}

impl<'a, T: Debug> Debug for TryMutexGuard<'a, T> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.debug_struct("TryMutexGuard")
            .field("data", &*self)
            .finish()
    }
}

impl<'a, T: Display> Display for TryMutexGuard<'a, T> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        (**self).fmt(f)
    }
}

impl<T> UnwindSafe for TryMutex<T> {}
impl<T> RefUnwindSafe for TryMutex<T> {}
unsafe impl<T: Send> Send for TryMutex<T> {}
unsafe impl<T: Send> Sync for TryMutex<T> {}
unsafe impl<'a, T: Sync> Sync for TryMutexGuard<'a, T> {}

impl<T> From<T> for TryMutex<T> {
    fn from(t: T) -> Self {
        TryMutex::new(t)
    }
}