use std::fmt;
use std::ops::Deref;
use std::sync::Arc;
use crate::rwlock::OwnedMappedRwLockReadGuard;
use crate::rwlock::RwLock;
impl<T: ?Sized> RwLock<T> {
pub async fn read_owned(self: Arc<Self>) -> OwnedRwLockReadGuard<T> {
self.s.acquire(1).await;
OwnedRwLockReadGuard { lock: self }
}
pub fn try_read_owned(self: Arc<Self>) -> Option<OwnedRwLockReadGuard<T>> {
if self.s.try_acquire(1) {
Some(OwnedRwLockReadGuard { lock: self })
} else {
None
}
}
}
#[must_use = "if unused the RwLock will immediately unlock"]
pub struct OwnedRwLockReadGuard<T: ?Sized> {
pub(super) lock: Arc<RwLock<T>>,
}
unsafe impl<T: ?Sized + Sync> Send for OwnedRwLockReadGuard<T> {}
unsafe impl<T: ?Sized + Send + Sync> Sync for OwnedRwLockReadGuard<T> {}
impl<T: ?Sized> Drop for OwnedRwLockReadGuard<T> {
fn drop(&mut self) {
self.lock.s.release(1);
}
}
impl<T: ?Sized + fmt::Debug> fmt::Debug for OwnedRwLockReadGuard<T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Debug::fmt(&**self, f)
}
}
impl<T: ?Sized + fmt::Display> fmt::Display for OwnedRwLockReadGuard<T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Display::fmt(&**self, f)
}
}
impl<T: ?Sized> Deref for OwnedRwLockReadGuard<T> {
type Target = T;
fn deref(&self) -> &Self::Target {
unsafe { &*self.lock.c.get() }
}
}
impl<T: ?Sized> OwnedRwLockReadGuard<T> {
pub fn map<U, F>(orig: Self, f: F) -> OwnedMappedRwLockReadGuard<T, U>
where
F: FnOnce(&T) -> &U,
U: ?Sized,
{
let d = std::ptr::NonNull::from(f(unsafe { &*orig.lock.c.get() }));
let orig = std::mem::ManuallyDrop::new(orig);
let lock = unsafe { std::ptr::read(&orig.lock) };
OwnedMappedRwLockReadGuard::new(d, lock)
}
pub fn filter_map<U, F>(orig: Self, f: F) -> Result<OwnedMappedRwLockReadGuard<T, U>, Self>
where
F: FnOnce(&T) -> Option<&U>,
U: ?Sized,
{
match f(unsafe { &*orig.lock.c.get() }) {
Some(d) => {
let d = std::ptr::NonNull::from(d);
let orig = std::mem::ManuallyDrop::new(orig);
let lock = unsafe { std::ptr::read(&orig.lock) };
Ok(OwnedMappedRwLockReadGuard::new(d, lock))
}
None => Err(orig),
}
}
}