use std::cell::UnsafeCell;
use std::fmt::Debug;
use std::marker::PhantomData;
use std::panic::AssertUnwindSafe;
use lock_api::RawMutex;
use crate::handle_unwind::handle_unwind;
use crate::lockable::{Lockable, LockableGetMut, LockableIntoInner, OwnedLockable, RawLock};
use crate::poisonable::PoisonFlag;
use crate::{Keyable, ThreadKey};
use super::{Mutex, MutexGuard, MutexRef};
unsafe impl<T: ?Sized, R: RawMutex> RawLock for Mutex<T, R> {
fn poison(&self) {
self.poison.poison();
}
unsafe fn raw_write(&self) {
assert!(!self.poison.is_poisoned(), "The mutex has been killed");
let this = AssertUnwindSafe(self);
handle_unwind(|| this.raw.lock(), || self.poison())
}
unsafe fn raw_try_write(&self) -> bool {
if self.poison.is_poisoned() {
return false;
}
let this = AssertUnwindSafe(self);
handle_unwind(|| this.raw.try_lock(), || self.poison())
}
unsafe fn raw_unlock_write(&self) {
let this = AssertUnwindSafe(self);
handle_unwind(|| this.raw.unlock(), || self.poison())
}
#[mutants::skip]
#[cfg(not(tarpaulin_include))]
unsafe fn raw_read(&self) {
self.raw_write()
}
#[mutants::skip]
#[cfg(not(tarpaulin_include))]
unsafe fn raw_try_read(&self) -> bool {
self.raw_try_write()
}
#[mutants::skip]
#[cfg(not(tarpaulin_include))]
unsafe fn raw_unlock_read(&self) {
self.raw_unlock_write()
}
}
unsafe impl<T, R: RawMutex> Lockable for Mutex<T, R> {
type Guard<'g>
= MutexRef<'g, T, R>
where
Self: 'g;
type DataMut<'a>
= &'a mut T
where
Self: 'a;
fn get_ptrs<'a>(&'a self, ptrs: &mut Vec<&'a dyn RawLock>) {
ptrs.push(self);
}
unsafe fn guard(&self) -> Self::Guard<'_> {
MutexRef::new(self)
}
unsafe fn data_mut(&self) -> Self::DataMut<'_> {
self.data.get().as_mut().unwrap_unchecked()
}
}
impl<T, R: RawMutex> LockableIntoInner for Mutex<T, R> {
type Inner = T;
fn into_inner(self) -> Self::Inner {
self.into_inner()
}
}
impl<T, R: RawMutex> LockableGetMut for Mutex<T, R> {
type Inner<'a>
= &'a mut T
where
Self: 'a;
fn get_mut(&mut self) -> Self::Inner<'_> {
self.get_mut()
}
}
unsafe impl<T, R: RawMutex> OwnedLockable for Mutex<T, R> {}
impl<T, R: RawMutex> Mutex<T, R> {
#[must_use]
pub const fn new(data: T) -> Self {
Self {
raw: R::INIT,
poison: PoisonFlag::new(),
data: UnsafeCell::new(data),
}
}
#[must_use]
pub const unsafe fn raw(&self) -> &R {
&self.raw
}
}
#[mutants::skip]
#[cfg(not(tarpaulin_include))]
impl<T: ?Sized + Debug, R: RawMutex> Debug for Mutex<T, R> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
if let Some(value) = unsafe { self.try_lock_no_key() } {
f.debug_struct("Mutex").field("data", &&*value).finish()
} else {
struct LockedPlaceholder;
impl Debug for LockedPlaceholder {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str("<locked>")
}
}
f.debug_struct("Mutex")
.field("data", &LockedPlaceholder)
.finish()
}
}
}
impl<T: Default, R: RawMutex> Default for Mutex<T, R> {
fn default() -> Self {
Self::new(T::default())
}
}
impl<T, R: RawMutex> From<T> for Mutex<T, R> {
fn from(value: T) -> Self {
Self::new(value)
}
}
impl<T: ?Sized, R> AsMut<T> for Mutex<T, R> {
fn as_mut(&mut self) -> &mut T {
self.get_mut()
}
}
impl<T, R> Mutex<T, R> {
#[must_use]
pub fn into_inner(self) -> T {
self.data.into_inner()
}
}
impl<T: ?Sized, R> Mutex<T, R> {
#[must_use]
pub fn get_mut(&mut self) -> &mut T {
self.data.get_mut()
}
}
impl<T: ?Sized, R: RawMutex> Mutex<T, R> {
pub fn scoped_lock<'a, Ret>(
&'a self,
key: impl Keyable,
f: impl FnOnce(&'a mut T) -> Ret,
) -> Ret {
unsafe {
self.raw_write();
let r = handle_unwind(
|| f(self.data.get().as_mut().unwrap_unchecked()),
|| self.raw_unlock_write(),
);
drop(key);
self.raw_unlock_write();
r
}
}
pub fn scoped_try_lock<'a, Key: Keyable, Ret>(
&'a self,
key: Key,
f: impl FnOnce(&'a mut T) -> Ret,
) -> Result<Ret, Key> {
unsafe {
if !self.raw_try_write() {
return Err(key);
}
let r = handle_unwind(
|| f(self.data.get().as_mut().unwrap_unchecked()),
|| self.raw_unlock_write(),
);
drop(key);
self.raw_unlock_write();
Ok(r)
}
}
}
impl<T: ?Sized, R: RawMutex> Mutex<T, R> {
pub fn lock(&self, key: ThreadKey) -> MutexGuard<'_, T, R> {
unsafe {
self.raw_write();
MutexGuard::new(self, key)
}
}
pub fn try_lock(&self, key: ThreadKey) -> Result<MutexGuard<'_, T, R>, ThreadKey> {
unsafe {
if self.raw_try_write() {
Ok(MutexGuard::new(self, key))
} else {
Err(key)
}
}
}
#[cfg(test)]
pub(crate) fn is_locked(&self) -> bool {
self.raw.is_locked()
}
pub(crate) unsafe fn try_lock_no_key(&self) -> Option<MutexRef<'_, T, R>> {
self.raw_try_write().then_some(MutexRef(self, PhantomData))
}
#[must_use]
pub fn unlock(guard: MutexGuard<'_, T, R>) -> ThreadKey {
drop(guard.mutex);
guard.thread_key
}
}
unsafe impl<R: RawMutex + Send, T: ?Sized + Send> Send for Mutex<T, R> {}
unsafe impl<R: RawMutex + Sync, T: ?Sized + Send> Sync for Mutex<T, R> {}