use std::{
cell::UnsafeCell,
fmt,
ops::{Deref, DerefMut},
};
use crate::fiber::{Latch, LatchGuard};
pub struct Mutex<T: ?Sized> {
latch: Latch,
data: UnsafeCell<T>,
}
impl<T: ?Sized> Mutex<T> {
pub fn new(t: T) -> Mutex<T>
where
T: Sized,
{
Mutex {
latch: Latch::new(),
data: UnsafeCell::new(t),
}
}
pub fn lock(&self) -> MutexGuard<'_, T> {
unsafe {
MutexGuard::new(self, self.latch.lock())
}
}
pub fn try_lock(&self) -> Option<MutexGuard<'_, T>> {
unsafe {
self.latch.try_lock().map(|guard| MutexGuard::new(self, guard))
}
}
pub fn unlock(guard: MutexGuard<'_, T>) {
drop(guard);
}
pub fn into_inner(self) -> T
where
T: Sized,
{
self.data.into_inner()
}
pub fn get_mut(&mut self) -> &mut T {
self.data.get_mut()
}
}
impl<T> From<T> for Mutex<T> {
fn from(t: T) -> Self {
Mutex::new(t)
}
}
impl<T: ?Sized + Default> Default for Mutex<T> {
fn default() -> Mutex<T> {
Mutex::new(Default::default())
}
}
impl<T: ?Sized + fmt::Debug> fmt::Debug for Mutex<T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let mut d = f.debug_struct("Mutex");
match self.try_lock() {
Some(guard) => {
d.field("data", &&*guard);
}
None => {
struct LockedPlaceholder;
impl fmt::Debug for LockedPlaceholder {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("<locked>")
}
}
d.field("data", &LockedPlaceholder);
}
}
d.finish_non_exhaustive()
}
}
pub struct MutexGuard<'a, T: ?Sized + 'a> {
lock: &'a Mutex<T>,
_latch_guard: LatchGuard,
}
impl<'mutex, T: ?Sized> MutexGuard<'mutex, T> {
unsafe fn new(lock: &'mutex Mutex<T>, _latch_guard: LatchGuard) -> Self {
Self { lock, _latch_guard }
}
}
impl<T: ?Sized> Deref for MutexGuard<'_, T> {
type Target = T;
fn deref(&self) -> &T {
unsafe { &*self.lock.data.get() }
}
}
impl<T: ?Sized> DerefMut for MutexGuard<'_, T> {
fn deref_mut(&mut self) -> &mut T {
unsafe { &mut *self.lock.data.get() }
}
}
impl<T: ?Sized + fmt::Debug> fmt::Debug for MutexGuard<'_, T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Debug::fmt(&**self, f)
}
}
impl<T: ?Sized + fmt::Display> fmt::Display for MutexGuard<'_, T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Display::fmt(&**self, f)
}
}