use parking_lot::{
lock_api::{
RawMutex as _,
RawMutexFair as _,
RawMutexTimed as _,
},
RawMutex,
};
use core::{
cell::UnsafeCell,
fmt,
mem,
ops::{Deref, DerefMut},
marker::PhantomData,
time::Duration,
};
use std::time::Instant;
#[cfg(feature = "owning_ref_support")]
use owning_ref::StableAddress;
#[cfg(feature = "serde_support")]
use serde::{Deserialize, Deserializer, Serialize, Serializer};
pub struct Mutex<T: ?Sized> {
raw: RawMutex,
data: UnsafeCell<T>,
}
unsafe impl<T: ?Sized + Send> Send for Mutex<T> {}
unsafe impl<T: ?Sized + Send> Sync for Mutex<T> {}
impl<T> Mutex<T> {
#[inline]
pub const fn new(val: T) -> Mutex<T> {
Mutex {
raw: RawMutex::INIT,
data: UnsafeCell::new(val),
}
}
#[inline]
pub fn into_inner(self) -> T {
self.data.into_inner()
}
}
impl<T: ?Sized> Mutex<T> {
#[inline]
unsafe fn guard(&self) -> MutexGuard<'_, T> {
MutexGuard {
mutex: self,
marker: PhantomData,
}
}
#[inline]
pub fn lock(&self) -> MutexGuard<'_, T> {
self.raw.lock();
unsafe { self.guard() }
}
#[inline]
pub fn try_lock(&self) -> Option<MutexGuard<'_, T>> {
if self.raw.try_lock() {
Some(unsafe { self.guard() })
} else {
None
}
}
#[inline]
pub fn get_mut(&mut self) -> &mut T {
unsafe { &mut *self.data.get() }
}
#[inline]
pub unsafe fn force_unlock(&self) {
self.raw.unlock();
}
#[inline]
pub unsafe fn raw(&self) -> &RawMutex {
&self.raw
}
}
impl<T: ?Sized> Mutex<T> {
#[inline]
pub unsafe fn force_unlock_fair(&self) {
self.raw.unlock_fair();
}
}
impl<T: ?Sized> Mutex<T> {
#[inline]
pub fn try_lock_for(&self, timeout: Duration) -> Option<MutexGuard<'_, T>> {
if self.raw.try_lock_for(timeout) {
Some(unsafe { self.guard() })
} else {
None
}
}
#[inline]
pub fn try_lock_until(&self, timeout: Instant) -> Option<MutexGuard<'_, T>> {
if self.raw.try_lock_until(timeout) {
Some(unsafe { self.guard() })
} else {
None
}
}
}
impl<T: ?Sized + Default> Default for Mutex<T> {
#[inline]
fn default() -> Mutex<T> {
Mutex::new(Default::default())
}
}
impl<T> From<T> for Mutex<T> {
#[inline]
fn from(t: T) -> Mutex<T> {
Mutex::new(t)
}
}
impl<T: ?Sized + fmt::Debug> fmt::Debug for Mutex<T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self.try_lock() {
Some(guard) => f.debug_struct("Mutex").field("data", &&*guard).finish(),
None => {
struct LockedPlaceholder;
impl fmt::Debug for LockedPlaceholder {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("<locked>")
}
}
f.debug_struct("Mutex")
.field("data", &LockedPlaceholder)
.finish()
}
}
}
}
#[cfg(feature = "serde_support")]
impl<T> Serialize for Mutex<T>
where
T: Serialize + ?Sized,
{
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
self.lock().serialize(serializer)
}
}
#[cfg(feature = "serde_support")]
impl<'de, T> Deserialize<'de> for Mutex<T>
where
T: Deserialize<'de> + ?Sized,
{
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
Deserialize::deserialize(deserializer).map(Mutex::new)
}
}
#[must_use = "if unused the Mutex will immediately unlock"]
pub struct MutexGuard<'a, T: ?Sized> {
mutex: &'a Mutex<T>,
marker: PhantomData<(&'a mut T, *mut ())>,
}
unsafe impl<'a, T: ?Sized + Sync + 'a> Sync for MutexGuard<'a, T> {}
impl<'a, T: ?Sized + 'a> MutexGuard<'a, T> {
pub fn mutex(s: &Self) -> &'a Mutex<T> {
s.mutex
}
#[inline]
pub fn map<U: ?Sized, F>(s: Self, f: F) -> MappedMutexGuard<'a, U>
where
F: FnOnce(&mut T) -> &mut U,
{
let raw = &s.mutex.raw;
let data = f(unsafe { &mut *s.mutex.data.get() });
mem::forget(s);
MappedMutexGuard {
raw,
data,
marker: PhantomData,
}
}
#[inline]
pub fn try_map<U: ?Sized, F>(s: Self, f: F) -> Result<MappedMutexGuard<'a, U>, Self>
where
F: FnOnce(&mut T) -> Option<&mut U>,
{
let raw = &s.mutex.raw;
let data = match f(unsafe { &mut *s.mutex.data.get() }) {
Some(data) => data,
None => return Err(s),
};
mem::forget(s);
Ok(MappedMutexGuard {
raw,
data,
marker: PhantomData,
})
}
#[inline]
pub fn unlocked<F, U>(s: &mut Self, f: F) -> U
where
F: FnOnce() -> U,
{
s.mutex.raw.unlock();
defer!(s.mutex.raw.lock());
f()
}
}
impl<'a, T: ?Sized + 'a> MutexGuard<'a, T> {
#[inline]
pub fn unlock_fair(s: Self) {
s.mutex.raw.unlock_fair();
mem::forget(s);
}
#[inline]
pub fn unlocked_fair<F, U>(s: &mut Self, f: F) -> U
where
F: FnOnce() -> U,
{
s.mutex.raw.unlock_fair();
defer!(s.mutex.raw.lock());
f()
}
#[inline]
pub fn bump(s: &mut Self) {
s.mutex.raw.bump();
}
}
impl<'a, T: ?Sized + 'a> Deref for MutexGuard<'a, T> {
type Target = T;
#[inline]
fn deref(&self) -> &T {
unsafe { &*self.mutex.data.get() }
}
}
impl<'a, T: ?Sized + 'a> DerefMut for MutexGuard<'a, T> {
#[inline]
fn deref_mut(&mut self) -> &mut T {
unsafe { &mut *self.mutex.data.get() }
}
}
impl<'a, T: ?Sized + 'a> Drop for MutexGuard<'a, T> {
#[inline]
fn drop(&mut self) {
self.mutex.raw.unlock();
}
}
impl<'a, T: fmt::Debug + ?Sized + 'a> fmt::Debug for MutexGuard<'a, T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Debug::fmt(&**self, f)
}
}
impl<'a, T: fmt::Display + ?Sized + 'a> fmt::Display for MutexGuard<'a, T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
(**self).fmt(f)
}
}
#[cfg(feature = "owning_ref_support")]
unsafe impl<'a, T: ?Sized + 'a> StableAddress for MutexGuard<'a, T> {}
#[must_use = "if unused the Mutex will immediately unlock"]
pub struct MappedMutexGuard<'a, T: ?Sized> {
raw: &'a RawMutex,
data: *mut T,
marker: PhantomData<&'a mut T>,
}
unsafe impl<'a, T: ?Sized + Sync + 'a> Sync
for MappedMutexGuard<'a, T>
{
}
impl<'a, T: ?Sized + 'a> MappedMutexGuard<'a, T> {
#[inline]
pub fn map<U: ?Sized, F>(s: Self, f: F) -> MappedMutexGuard<'a, U>
where
F: FnOnce(&mut T) -> &mut U,
{
let raw = s.raw;
let data = f(unsafe { &mut *s.data });
mem::forget(s);
MappedMutexGuard {
raw,
data,
marker: PhantomData,
}
}
#[inline]
pub fn try_map<U: ?Sized, F>(s: Self, f: F) -> Result<MappedMutexGuard<'a, U>, Self>
where
F: FnOnce(&mut T) -> Option<&mut U>,
{
let raw = s.raw;
let data = match f(unsafe { &mut *s.data }) {
Some(data) => data,
None => return Err(s),
};
mem::forget(s);
Ok(MappedMutexGuard {
raw,
data,
marker: PhantomData,
})
}
}
impl<'a, T: ?Sized + 'a> MappedMutexGuard<'a, T> {
#[inline]
pub fn unlock_fair(s: Self) {
s.raw.unlock_fair();
mem::forget(s);
}
}
impl<'a, T: ?Sized + 'a> Deref for MappedMutexGuard<'a, T> {
type Target = T;
#[inline]
fn deref(&self) -> &T {
unsafe { &*self.data }
}
}
impl<'a, T: ?Sized + 'a> DerefMut for MappedMutexGuard<'a, T> {
#[inline]
fn deref_mut(&mut self) -> &mut T {
unsafe { &mut *self.data }
}
}
impl<'a, T: ?Sized + 'a> Drop for MappedMutexGuard<'a, T> {
#[inline]
fn drop(&mut self) {
self.raw.unlock();
}
}
impl<'a, T: fmt::Debug + ?Sized + 'a> fmt::Debug for MappedMutexGuard<'a, T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Debug::fmt(&**self, f)
}
}
impl<'a, T: fmt::Display + ?Sized + 'a> fmt::Display
for MappedMutexGuard<'a, T>
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
(**self).fmt(f)
}
}
#[cfg(feature = "owning_ref_support")]
unsafe impl<'a, T: ?Sized + 'a> StableAddress for MappedMutexGuard<'a, T> {}
#[cfg(test)]
mod tests {
use crate::Mutex;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::mpsc::channel;
use std::sync::Arc;
use std::thread;
#[cfg(feature = "serde_support")]
use bincode::{deserialize, serialize};
#[derive(Eq, PartialEq, Debug)]
struct NonCopy(i32);
#[test]
fn smoke() {
let m = Mutex::new(());
drop(m.lock());
drop(m.lock());
}
#[test]
fn lots_and_lots() {
const J: u32 = 1000;
const K: u32 = 3;
let m = Arc::new(Mutex::new(0));
fn inc(m: &Mutex<u32>) {
for _ in 0..J {
*m.lock() += 1;
}
}
let (tx, rx) = channel();
for _ in 0..K {
let tx2 = tx.clone();
let m2 = m.clone();
thread::spawn(move || {
inc(&m2);
tx2.send(()).unwrap();
});
let tx2 = tx.clone();
let m2 = m.clone();
thread::spawn(move || {
inc(&m2);
tx2.send(()).unwrap();
});
}
drop(tx);
for _ in 0..2 * K {
rx.recv().unwrap();
}
assert_eq!(*m.lock(), J * K * 2);
}
#[test]
fn try_lock() {
let m = Mutex::new(());
*m.try_lock().unwrap() = ();
}
#[test]
fn test_into_inner() {
let m = Mutex::new(NonCopy(10));
assert_eq!(m.into_inner(), NonCopy(10));
}
#[test]
fn test_into_inner_drop() {
struct Foo(Arc<AtomicUsize>);
impl Drop for Foo {
fn drop(&mut self) {
self.0.fetch_add(1, Ordering::SeqCst);
}
}
let num_drops = Arc::new(AtomicUsize::new(0));
let m = Mutex::new(Foo(num_drops.clone()));
assert_eq!(num_drops.load(Ordering::SeqCst), 0);
{
let _inner = m.into_inner();
assert_eq!(num_drops.load(Ordering::SeqCst), 0);
}
assert_eq!(num_drops.load(Ordering::SeqCst), 1);
}
#[test]
fn test_get_mut() {
let mut m = Mutex::new(NonCopy(10));
*m.get_mut() = NonCopy(20);
assert_eq!(m.into_inner(), NonCopy(20));
}
#[test]
fn test_mutex_arc_nested() {
let arc = Arc::new(Mutex::new(1));
let arc2 = Arc::new(Mutex::new(arc));
let (tx, rx) = channel();
let _t = thread::spawn(move || {
let lock = arc2.lock();
let lock2 = lock.lock();
assert_eq!(*lock2, 1);
tx.send(()).unwrap();
});
rx.recv().unwrap();
}
#[test]
fn test_mutex_arc_access_in_unwind() {
let arc = Arc::new(Mutex::new(1));
let arc2 = arc.clone();
let _ = thread::spawn(move || {
struct Unwinder {
i: Arc<Mutex<i32>>,
}
impl Drop for Unwinder {
fn drop(&mut self) {
*self.i.lock() += 1;
}
}
let _u = Unwinder { i: arc2 };
panic!();
})
.join();
let lock = arc.lock();
assert_eq!(*lock, 2);
}
#[test]
fn test_mutex_unsized() {
let mutex: &Mutex<[i32]> = &Mutex::new([1, 2, 3]);
{
let b = &mut *mutex.lock();
b[0] = 4;
b[2] = 5;
}
let comp: &[i32] = &[4, 2, 5];
assert_eq!(&*mutex.lock(), comp);
}
#[test]
fn test_mutexguard_sync() {
fn sync<T: Sync>(_: T) {}
let mutex = Mutex::new(());
sync(mutex.lock());
}
#[test]
fn test_mutex_debug() {
let mutex = Mutex::new(vec![0u8, 10]);
assert_eq!(format!("{:?}", mutex), "Mutex { data: [0, 10] }");
let _lock = mutex.lock();
assert_eq!(format!("{:?}", mutex), "Mutex { data: <locked> }");
}
#[cfg(feature = "serde_support")]
#[test]
fn test_serde() {
let contents: Vec<u8> = vec![0, 1, 2];
let mutex = Mutex::new(contents.clone());
let serialized = serialize(&mutex).unwrap();
let deserialized: Mutex<Vec<u8>> = deserialize(&serialized).unwrap();
assert_eq!(*(mutex.lock()), *(deserialized.lock()));
assert_eq!(contents, *(deserialized.lock()));
}
}