use core::cell::UnsafeCell;
use core::cmp::Ordering;
use core::fmt::{Debug, Display};
use core::ops::{Deref, DerefMut};
use crate::spin::{SpinLock, SpinLockGuard};
pub struct Mutex<T: ?Sized> {
lock: SpinLock,
data: UnsafeCell<T>,
}
unsafe impl<T: ?Sized + Send> Send for Mutex<T> {}
unsafe impl<T: ?Sized + Send> Sync for Mutex<T> {}
#[must_use = "if unused, the lock will release automatically"]
pub struct MutexGuard<'a, T: ?Sized> {
mutex: &'a Mutex<T>,
_lock: SpinLockGuard<'a>,
}
impl<T: Debug> Debug for MutexGuard<'_, T> {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
write!(f, "MutexGuard({:?})", unsafe { &*self.mutex.data.get() })
}
}
impl<T: Display> Display for MutexGuard<'_, T> {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
unsafe { <T as Display>::fmt(self.mutex.data.get().as_ref().unwrap(), f) }
}
}
impl<T: PartialEq> PartialEq for MutexGuard<'_, T> {
fn eq(&self, other: &Self) -> bool {
unsafe { self.mutex.data.get().as_ref().unwrap().eq(other.mutex.data.get().as_ref().unwrap()) }
}
}
impl<T: PartialOrd> PartialOrd for MutexGuard<'_, T> {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
unsafe { self.mutex.data.get().as_ref().unwrap().partial_cmp(other.mutex.data.get().as_ref().unwrap()) }
}
}
unsafe impl<T: ?Sized + Send> Send for MutexGuard<'_, T> {}
unsafe impl<T: ?Sized + Sync> Sync for MutexGuard<'_, T> {}
impl<T> Deref for MutexGuard<'_, T> {
type Target = T;
fn deref(&self) -> &Self::Target {
unsafe { &*self.mutex.data.get() }
}
}
impl<T> DerefMut for MutexGuard<'_, T> {
fn deref_mut(&mut self) -> &mut Self::Target {
unsafe { &mut *self.mutex.data.get() }
}
}
impl<T> Mutex<T> {
pub const fn new(val: T) -> Self {
Self {
lock: SpinLock::new(),
data: UnsafeCell::new(val),
}
}
pub fn into_inner(self) -> T {
UnsafeCell::into_inner(self.data)
}
}
impl<T: ?Sized> Mutex<T> {
pub fn try_lock(&self) -> Option<MutexGuard<'_, T>> {
self.lock.try_lock().map(|guard| {
MutexGuard { _lock: guard, mutex: self }
})
}
pub fn lock(&self) -> MutexGuard<'_, T> {
let guard = self.lock.lock();
MutexGuard { _lock: guard, mutex: self }
}
#[inline]
pub const fn get_mut(&mut self) -> &mut T {
self.data.get_mut()
}
#[inline]
pub fn is_locked(&self) -> bool {
self.lock.is_locked()
}
}
impl<T: Default> Default for Mutex<T> {
#[inline]
fn default() -> Self {
Self::new(T::default())
}
}
pub (crate) fn guard_to_mutex<'a, T>(lock: MutexGuard<'a, T>) -> &'a Mutex<T> {
lock.mutex
}