use std::cell::UnsafeCell;
use std::fmt::Debug;
use std::marker::PhantomData;
use std::panic::AssertUnwindSafe;
use lock_api::RawRwLock;
use crate::handle_unwind::handle_unwind;
use crate::lockable::{
Lockable, LockableGetMut, LockableIntoInner, OwnedLockable, RawLock, Sharable,
};
use crate::{Keyable, ThreadKey};
use super::{PoisonFlag, RwLock, RwLockReadGuard, RwLockReadRef, RwLockWriteGuard, RwLockWriteRef};
unsafe impl<T: ?Sized, R: RawRwLock> RawLock for RwLock<T, R> {
fn poison(&self) {
self.poison.poison();
}
unsafe fn raw_write(&self) {
assert!(
!self.poison.is_poisoned(),
"The read-write lock has been killed"
);
let this = AssertUnwindSafe(self);
handle_unwind(|| this.raw.lock_exclusive(), || 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_exclusive(), || self.poison())
}
unsafe fn raw_unlock_write(&self) {
let this = AssertUnwindSafe(self);
handle_unwind(|| this.raw.unlock_exclusive(), || self.poison())
}
unsafe fn raw_read(&self) {
assert!(
!self.poison.is_poisoned(),
"The read-write lock has been killed"
);
let this = AssertUnwindSafe(self);
handle_unwind(|| this.raw.lock_shared(), || self.poison())
}
unsafe fn raw_try_read(&self) -> bool {
if self.poison.is_poisoned() {
return false;
}
let this = AssertUnwindSafe(self);
handle_unwind(|| this.raw.try_lock_shared(), || self.poison())
}
unsafe fn raw_unlock_read(&self) {
let this = AssertUnwindSafe(self);
handle_unwind(|| this.raw.unlock_shared(), || self.poison())
}
}
unsafe impl<T, R: RawRwLock> Lockable for RwLock<T, R> {
type Guard<'g>
= RwLockWriteRef<'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<'_> {
RwLockWriteRef::new(self)
}
unsafe fn data_mut(&self) -> Self::DataMut<'_> {
self.data.get().as_mut().unwrap_unchecked()
}
}
unsafe impl<T, R: RawRwLock> Sharable for RwLock<T, R> {
type ReadGuard<'g>
= RwLockReadRef<'g, T, R>
where
Self: 'g;
type DataRef<'a>
= &'a T
where
Self: 'a;
unsafe fn read_guard(&self) -> Self::ReadGuard<'_> {
RwLockReadRef::new(self)
}
unsafe fn data_ref(&self) -> Self::DataRef<'_> {
self.data.get().as_ref().unwrap_unchecked()
}
}
unsafe impl<T, R: RawRwLock> OwnedLockable for RwLock<T, R> {}
impl<T, R: RawRwLock> LockableIntoInner for RwLock<T, R> {
type Inner = T;
fn into_inner(self) -> Self::Inner {
self.into_inner()
}
}
impl<T, R: RawRwLock> LockableGetMut for RwLock<T, R> {
type Inner<'a>
= &'a mut T
where
Self: 'a;
fn get_mut(&mut self) -> Self::Inner<'_> {
AsMut::as_mut(self)
}
}
impl<T, R: RawRwLock> RwLock<T, R> {
#[must_use]
pub const fn new(data: T) -> Self {
Self {
data: UnsafeCell::new(data),
poison: PoisonFlag::new(),
raw: R::INIT,
}
}
}
#[mutants::skip]
#[cfg(not(tarpaulin_include))]
impl<T: Debug, R: RawRwLock> Debug for RwLock<T, R> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
if let Some(value) = unsafe { self.try_read_no_key() } {
f.debug_struct("RwLock").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("RwLock")
.field("data", &LockedPlaceholder)
.finish()
}
}
}
impl<T: Default, R: RawRwLock> Default for RwLock<T, R> {
fn default() -> Self {
Self::new(T::default())
}
}
impl<T, R: RawRwLock> From<T> for RwLock<T, R> {
fn from(value: T) -> Self {
Self::new(value)
}
}
impl<T: ?Sized, R> AsMut<T> for RwLock<T, R> {
fn as_mut(&mut self) -> &mut T {
self.data.get_mut()
}
}
impl<T, R> RwLock<T, R> {
#[must_use]
pub fn into_inner(self) -> T {
self.data.into_inner()
}
}
impl<T: ?Sized, R> RwLock<T, R> {
#[must_use]
pub fn get_mut(&mut self) -> &mut T {
self.data.get_mut()
}
}
impl<T: ?Sized, R: RawRwLock> RwLock<T, R> {
pub fn scoped_read<'a, Ret>(&'a self, key: impl Keyable, f: impl FnOnce(&'a T) -> Ret) -> Ret {
unsafe {
self.raw_read();
let r = handle_unwind(
|| f(self.data.get().as_ref().unwrap_unchecked()),
|| self.raw_unlock_read(),
);
drop(key);
self.raw_unlock_read();
r
}
}
pub fn scoped_try_read<'a, Key: Keyable, Ret>(
&'a self,
key: Key,
f: impl FnOnce(&'a T) -> Ret,
) -> Result<Ret, Key> {
unsafe {
if !self.raw_try_read() {
return Err(key);
}
let r = handle_unwind(
|| f(self.data.get().as_ref().unwrap_unchecked()),
|| self.raw_unlock_read(),
);
drop(key);
self.raw_unlock_read();
Ok(r)
}
}
pub fn scoped_write<'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_write<'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)
}
}
pub fn read(&self, key: ThreadKey) -> RwLockReadGuard<'_, T, R> {
unsafe {
self.raw_read();
RwLockReadGuard::new(self, key)
}
}
pub fn try_read(&self, key: ThreadKey) -> Result<RwLockReadGuard<'_, T, R>, ThreadKey> {
unsafe {
if self.raw_try_read() {
Ok(RwLockReadGuard::new(self, key))
} else {
Err(key)
}
}
}
pub(crate) unsafe fn try_read_no_key(&self) -> Option<RwLockReadRef<'_, T, R>> {
if self.raw_try_read() {
Some(RwLockReadRef(self, PhantomData))
} else {
None
}
}
#[cfg(test)]
pub(crate) unsafe fn try_write_no_key(&self) -> Option<RwLockWriteRef<'_, T, R>> {
if self.raw_try_write() {
Some(RwLockWriteRef(self, PhantomData))
} else {
None
}
}
pub fn write(&self, key: ThreadKey) -> RwLockWriteGuard<'_, T, R> {
unsafe {
self.raw_write();
RwLockWriteGuard::new(self, key)
}
}
pub fn try_write(&self, key: ThreadKey) -> Result<RwLockWriteGuard<'_, T, R>, ThreadKey> {
unsafe {
if self.raw_try_write() {
Ok(RwLockWriteGuard::new(self, key))
} else {
Err(key)
}
}
}
#[cfg(test)]
pub(crate) fn is_locked(&self) -> bool {
self.raw.is_locked()
}
#[must_use]
pub fn unlock_read(guard: RwLockReadGuard<'_, T, R>) -> ThreadKey {
drop(guard.rwlock);
guard.thread_key
}
#[must_use]
pub fn unlock_write(guard: RwLockWriteGuard<'_, T, R>) -> ThreadKey {
drop(guard.rwlock);
guard.thread_key
}
}
unsafe impl<R: RawRwLock + Send, T: ?Sized + Send> Send for RwLock<T, R> {}
unsafe impl<R: RawRwLock + Sync, T: ?Sized + Send> Sync for RwLock<T, R> {}