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
#![cfg(any(target_os = "macos", target_os = "ios"))]
#![no_std]
#![cfg_attr(feature = "nightly", feature(coerce_unsized, unsize))]

use core::cell::UnsafeCell;
use core::default::Default;
use core::fmt::{self, Debug, Display, Formatter};
use core::marker::PhantomData;
use core::ops::{Deref, DerefMut, Drop};

#[allow(non_camel_case_types)]
pub mod sys {
    #[repr(C)]
    pub struct os_unfair_lock(pub u32);

    pub type os_unfair_lock_t = *mut os_unfair_lock;
    pub type os_unfair_lock_s = os_unfair_lock;

    pub const OS_UNFAIR_LOCK_INIT: os_unfair_lock = os_unfair_lock(0);

    extern "C" {
        // part of libSystem, no link needed
        pub fn os_unfair_lock_lock(lock: os_unfair_lock_t);
        pub fn os_unfair_lock_unlock(lock: os_unfair_lock_t);
        pub fn os_unfair_lock_trylock(lock: os_unfair_lock_t) -> bool;
        pub fn os_unfair_lock_assert_owner(lock: os_unfair_lock_t);
        pub fn os_unfair_lock_assert_not_owner(lock: os_unfair_lock_t);
    }
}

pub struct Mutex<T: ?Sized> {
    pub lock: UnsafeCell<sys::os_unfair_lock>,
    pub cell: UnsafeCell<T>,
}

struct CantSendMutexGuardBetweenThreads;

pub struct MutexGuard<'a, T: ?Sized> {
    pub mutex: &'a Mutex<T>,
    // could just be *const (), but this produces a better error message
    pd: PhantomData<*const CantSendMutexGuardBetweenThreads>,
}

unsafe impl<T: ?Sized + Send> Sync for Mutex<T> {}
unsafe impl<T: ?Sized + Send> Send for Mutex<T> {}

impl<T: ?Sized> Mutex<T> {
    #[inline]
    pub const fn new(value: T) -> Self
    where
        T: Sized,
    {
        Mutex {
            lock: UnsafeCell::new(sys::OS_UNFAIR_LOCK_INIT),
            cell: UnsafeCell::new(value),
        }
    }
    #[inline]
    pub fn lock<'a>(&'a self) -> MutexGuard<'a, T> {
        unsafe {
            sys::os_unfair_lock_lock(self.lock.get());
        }
        MutexGuard {
            mutex: self,
            pd: PhantomData,
        }
    }
    #[inline]
    pub fn try_lock<'a>(&'a self) -> Option<MutexGuard<'a, T>> {
        let ok = unsafe { sys::os_unfair_lock_trylock(self.lock.get()) };
        if ok {
            Some(MutexGuard {
                mutex: self,
                pd: PhantomData,
            })
        } else {
            None
        }
    }
    #[inline]
    pub fn assert_not_owner(&self) {
        unsafe {
            sys::os_unfair_lock_assert_not_owner(self.lock.get());
        }
    }
    #[inline]
    pub fn into_inner(self) -> T
    where
        T: Sized,
    {
        self.cell.into_inner()
    }
}

// It's (potentially) Sync but not Send, because os_unfair_lock_unlock must be called from the
// locking thread.
unsafe impl<'a, T: ?Sized + Sync> Sync for MutexGuard<'a, T> {}

impl<'a, T: ?Sized> Deref for MutexGuard<'a, T> {
    type Target = T;
    #[inline]
    fn deref(&self) -> &T {
        unsafe { &*self.mutex.cell.get() }
    }
}

impl<'a, T: ?Sized> DerefMut for MutexGuard<'a, T> {
    #[inline]
    fn deref_mut(&mut self) -> &mut T {
        unsafe { &mut *self.mutex.cell.get() }
    }
}

impl<'a, T: ?Sized> Drop for MutexGuard<'a, T> {
    #[inline]
    fn drop(&mut self) {
        unsafe {
            sys::os_unfair_lock_unlock(self.mutex.lock.get());
        }
    }
}

// extra impls: Mutex

impl<T: ?Sized + Default> Default for Mutex<T> {
    #[inline]
    fn default() -> Self {
        Mutex::new(T::default())
    }
}

impl<T: ?Sized + Debug> Debug for Mutex<T> {
    #[inline]
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        self.lock().fmt(f)
    }
}

impl<T: ?Sized + Display> Display for Mutex<T> {
    #[inline]
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        self.lock().fmt(f)
    }
}

impl<T> From<T> for Mutex<T> {
    #[inline]
    fn from(t: T) -> Mutex<T> {
        Mutex::new(t)
    }
}

#[cfg(feature = "nightly")]
impl<T, U> core::ops::CoerceUnsized<Mutex<U>> for Mutex<T> where T: core::ops::CoerceUnsized<U> {}

// extra impls: MutexGuard

impl<'a, T: ?Sized + Debug> Debug for MutexGuard<'a, T> {
    #[inline]
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        (**self).fmt(f)
    }
}

impl<'a, T: ?Sized + Display> Display for MutexGuard<'a, T> {
    #[inline]
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        (**self).fmt(f)
    }
}

#[cfg(feature = "nightly")]
impl<'a, T: ?Sized, U: ?Sized> core::ops::CoerceUnsized<MutexGuard<'a, U>> for MutexGuard<'a, T> where
    T: core::marker::Unsize<U>
{
}

#[cfg(test)]
mod tests {
    use super::Mutex;
    const TEST_CONST: Mutex<u32> = Mutex::new(42);
    #[test]
    fn basics() {
        let m = TEST_CONST;
        *m.lock() += 1;
        {
            let mut g = m.try_lock().unwrap();
            *g += 1;
            assert!(m.try_lock().is_none());
        }
        m.assert_not_owner();
        assert_eq!(*m.lock(), 44);
        assert_eq!(m.into_inner(), 44);
    }
    #[test]
    #[cfg(feature = "nightly")]
    fn unsize() {
        use super::MutexGuard;
        let m: Mutex<[u8; 1]> = Mutex::new([100]);
        (&m as &Mutex<[u8]>).lock()[0] += 1;
        (m.lock() as MutexGuard<'_, [u8]>)[0] += 1;
        let n: Mutex<&'static [u8; 1]> = Mutex::new(&[200]);
        let _: Mutex<&'static [u8]> = n;
    }
}