use crate::sync::batch_semaphore::{Semaphore, TryAcquireError};
use crate::sync::mutex::TryLockError;
use std::cell::UnsafeCell;
use std::fmt;
use std::marker;
use std::mem;
use std::ops;
#[cfg(not(loom))]
const MAX_READS: usize = 32;
#[cfg(loom)]
const MAX_READS: usize = 10;
#[derive(Debug)]
pub struct RwLock<T: ?Sized> {
s: Semaphore,
c: UnsafeCell<T>,
}
pub struct RwLockReadGuard<'a, T: ?Sized> {
s: &'a Semaphore,
data: *const T,
marker: marker::PhantomData<&'a T>,
}
impl<'a, T> RwLockReadGuard<'a, T> {
#[inline]
pub fn map<F, U: ?Sized>(this: Self, f: F) -> RwLockReadGuard<'a, U>
where
F: FnOnce(&T) -> &U,
{
let data = f(&*this) as *const U;
let s = this.s;
mem::forget(this);
RwLockReadGuard {
s,
data,
marker: marker::PhantomData,
}
}
#[inline]
pub fn try_map<F, U: ?Sized>(this: Self, f: F) -> Result<RwLockReadGuard<'a, U>, Self>
where
F: FnOnce(&T) -> Option<&U>,
{
let data = match f(&*this) {
Some(data) => data as *const U,
None => return Err(this),
};
let s = this.s;
mem::forget(this);
Ok(RwLockReadGuard {
s,
data,
marker: marker::PhantomData,
})
}
}
impl<'a, T: ?Sized> fmt::Debug for RwLockReadGuard<'a, T>
where
T: fmt::Debug,
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Debug::fmt(&**self, f)
}
}
impl<'a, T: ?Sized> fmt::Display for RwLockReadGuard<'a, T>
where
T: fmt::Display,
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Display::fmt(&**self, f)
}
}
impl<'a, T: ?Sized> Drop for RwLockReadGuard<'a, T> {
fn drop(&mut self) {
self.s.release(1);
}
}
pub struct RwLockWriteGuard<'a, T: ?Sized> {
s: &'a Semaphore,
data: *mut T,
marker: marker::PhantomData<&'a mut T>,
}
impl<'a, T: ?Sized> RwLockWriteGuard<'a, T> {
pub fn downgrade(self) -> RwLockReadGuard<'a, T> {
let RwLockWriteGuard { s, data, .. } = self;
s.release(MAX_READS - 1);
mem::forget(self);
RwLockReadGuard {
s,
data,
marker: marker::PhantomData,
}
}
}
impl<'a, T: ?Sized> fmt::Debug for RwLockWriteGuard<'a, T>
where
T: fmt::Debug,
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Debug::fmt(&**self, f)
}
}
impl<'a, T: ?Sized> fmt::Display for RwLockWriteGuard<'a, T>
where
T: fmt::Display,
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Display::fmt(&**self, f)
}
}
impl<'a, T: ?Sized> Drop for RwLockWriteGuard<'a, T> {
fn drop(&mut self) {
self.s.release(MAX_READS);
}
}
#[test]
#[cfg(not(loom))]
fn bounds() {
fn check_send<T: Send>() {}
fn check_sync<T: Sync>() {}
fn check_unpin<T: Unpin>() {}
fn check_send_sync_val<T: Send + Sync>(_t: T) {}
check_send::<RwLock<u32>>();
check_sync::<RwLock<u32>>();
check_unpin::<RwLock<u32>>();
check_send::<RwLockReadGuard<'_, u32>>();
check_sync::<RwLockReadGuard<'_, u32>>();
check_unpin::<RwLockReadGuard<'_, u32>>();
check_send::<RwLockWriteGuard<'_, u32>>();
check_sync::<RwLockWriteGuard<'_, u32>>();
check_unpin::<RwLockWriteGuard<'_, u32>>();
let rwlock = RwLock::new(0);
check_send_sync_val(rwlock.read());
check_send_sync_val(rwlock.write());
}
unsafe impl<T> Send for RwLock<T> where T: ?Sized + Send {}
unsafe impl<T> Sync for RwLock<T> where T: ?Sized + Send + Sync {}
unsafe impl<T> Send for RwLockReadGuard<'_, T> where T: ?Sized + Sync {}
unsafe impl<T> Sync for RwLockReadGuard<'_, T> where T: ?Sized + Send + Sync {}
unsafe impl<T> Sync for RwLockWriteGuard<'_, T> where T: ?Sized + Send + Sync {}
unsafe impl<T> Send for RwLockWriteGuard<'_, T> where T: ?Sized + Send + Sync {}
impl<T: ?Sized> RwLock<T> {
pub fn new(value: T) -> RwLock<T>
where
T: Sized,
{
RwLock {
c: UnsafeCell::new(value),
s: Semaphore::new(MAX_READS),
}
}
#[cfg(all(feature = "parking_lot", not(all(loom, test))))]
#[cfg_attr(docsrs, doc(cfg(feature = "parking_lot")))]
pub const fn const_new(value: T) -> RwLock<T>
where
T: Sized,
{
RwLock {
c: UnsafeCell::new(value),
s: Semaphore::const_new(MAX_READS),
}
}
pub async fn read(&self) -> RwLockReadGuard<'_, T> {
self.s.acquire(1).await.unwrap_or_else(|_| {
unreachable!()
});
RwLockReadGuard {
s: &self.s,
data: self.c.get(),
marker: marker::PhantomData,
}
}
pub fn try_read(&self) -> Result<RwLockReadGuard<'_, T>, TryLockError> {
match self.s.try_acquire(1) {
Ok(permit) => permit,
Err(TryAcquireError::NoPermits) => return Err(TryLockError(())),
Err(TryAcquireError::Closed) => unreachable!(),
}
Ok(RwLockReadGuard {
s: &self.s,
data: self.c.get(),
marker: marker::PhantomData,
})
}
pub async fn write(&self) -> RwLockWriteGuard<'_, T> {
self.s.acquire(MAX_READS as u32).await.unwrap_or_else(|_| {
unreachable!()
});
RwLockWriteGuard {
s: &self.s,
data: self.c.get(),
marker: marker::PhantomData,
}
}
pub fn try_write(&self) -> Result<RwLockWriteGuard<'_, T>, TryLockError> {
match self.s.try_acquire(MAX_READS as u32) {
Ok(permit) => permit,
Err(TryAcquireError::NoPermits) => return Err(TryLockError(())),
Err(TryAcquireError::Closed) => unreachable!(),
}
Ok(RwLockWriteGuard {
s: &self.s,
data: self.c.get(),
marker: marker::PhantomData,
})
}
pub fn get_mut(&mut self) -> &mut T {
unsafe {
&mut *self.c.get()
}
}
pub fn into_inner(self) -> T
where
T: Sized,
{
self.c.into_inner()
}
}
impl<T: ?Sized> ops::Deref for RwLockReadGuard<'_, T> {
type Target = T;
fn deref(&self) -> &T {
unsafe { &*self.data }
}
}
impl<T: ?Sized> ops::Deref for RwLockWriteGuard<'_, T> {
type Target = T;
fn deref(&self) -> &T {
unsafe { &*self.data }
}
}
impl<T: ?Sized> ops::DerefMut for RwLockWriteGuard<'_, T> {
fn deref_mut(&mut self) -> &mut T {
unsafe { &mut *self.data }
}
}
impl<T> From<T> for RwLock<T> {
fn from(s: T) -> Self {
Self::new(s)
}
}
impl<T: ?Sized> Default for RwLock<T>
where
T: Default,
{
fn default() -> Self {
Self::new(T::default())
}
}