use super::{Permit, Semaphore};
use crate::{Result, SuspensionReason, signal::lock};
use std::{
marker::PhantomData,
ops::{Deref, DerefMut},
rc::Rc,
sync::Mutex as NativeMutex,
};
pub struct Mutex<T> {
value: NativeMutex<Option<T>>,
semaphore: Semaphore,
}
#[must_use = "dropping the guard immediately unlocks the mutex"]
pub struct MutexGuard<'a, T> {
pub(super) mutex: &'a Mutex<T>,
value: Option<T>,
_permit: Permit<'a>,
_affine: PhantomData<Rc<()>>,
}
impl<T> Mutex<T> {
pub fn new(value: T) -> Self {
Self::with_wait_capacity(value, super::DEFAULT_WAIT_CAPACITY)
.expect("default waiter capacity is positive")
}
pub fn with_wait_capacity(value: T, wait_capacity: usize) -> Result<Self> {
Ok(Self {
value: NativeMutex::new(Some(value)),
semaphore: Semaphore::with_wait_capacity(1, wait_capacity)?,
})
}
pub fn lock(&self) -> Result<MutexGuard<'_, T>> {
let permit = self.semaphore.acquire_for(SuspensionReason::Mutex)?;
Ok(self.guard(permit))
}
pub fn try_lock(&self) -> Result<MutexGuard<'_, T>> {
Ok(self.guard(self.semaphore.try_acquire()?))
}
fn guard<'a>(&'a self, permit: Permit<'a>) -> MutexGuard<'a, T> {
let value = lock(&self.value)
.take()
.expect("mutex permit owns its value");
MutexGuard {
mutex: self,
value: Some(value),
_permit: permit,
_affine: PhantomData,
}
}
pub fn waiting(&self) -> usize {
self.semaphore.waiting()
}
pub fn wait_capacity(&self) -> usize {
self.semaphore.wait_capacity()
}
}
impl<T: Default> Default for Mutex<T> {
fn default() -> Self {
Self::new(T::default())
}
}
impl<T> Deref for MutexGuard<'_, T> {
type Target = T;
fn deref(&self) -> &T {
self.value.as_ref().expect("live mutex guard")
}
}
impl<T> DerefMut for MutexGuard<'_, T> {
fn deref_mut(&mut self) -> &mut T {
self.value.as_mut().expect("live mutex guard")
}
}
impl<T> Drop for MutexGuard<'_, T> {
fn drop(&mut self) {
*lock(&self.mutex.value) = self.value.take();
}
}
#[cfg(test)]
#[path = "mutex_test.rs"]
mod mutex_test;