use core::cell::UnsafeCell;
use core::ops::{Deref, DerefMut};
use core::sync::atomic::AtomicBool;
use core::sync::atomic::Ordering::*;
pub struct Mutex<T> {
lock: AtomicBool,
data: UnsafeCell<T>,
}
#[must_use]
pub struct MutexGuard<'a, T: 'a> {
lock: &'a Mutex<T>,
}
unsafe impl<T: Send> Send for Mutex<T> {}
unsafe impl<T: Send> Sync for Mutex<T> {}
impl<'a, T> !Send for MutexGuard<'a, T> {}
unsafe impl<'a, T: Sync> Sync for MutexGuard<'a, T> {}
impl<T> Mutex<T> {
#[inline(always)]
pub const fn new(t: T) -> Self {
Self {
lock: AtomicBool::new(false),
data: UnsafeCell::new(t),
}
}
#[inline(always)]
pub fn try_lock(&self) -> Option<MutexGuard<T>> {
if !self.lock.swap(true, Acquire) {
Some(MutexGuard { lock: self })
} else {
None
}
}
#[inline(always)]
pub fn into_inner(self) -> T {
let Self { data, .. } = self;
unsafe { data.into_inner() }
}
#[inline(always)]
pub fn get_mut(&mut self) -> &mut T {
unsafe { &mut *self.data.get() }
}
}
impl<T: Default> Default for Mutex<T> {
#[inline(always)]
fn default() -> Self {
Mutex::new(Default::default())
}
}
impl<'a, T> Deref for MutexGuard<'a, T> {
type Target = T;
#[inline(always)]
fn deref(&self) -> &T {
unsafe { &*self.lock.data.get() }
}
}
impl<'a, T> DerefMut for MutexGuard<'a, T> {
#[inline(always)]
fn deref_mut(&mut self) -> &mut T {
unsafe { &mut *self.lock.data.get() }
}
}
impl<'a, T> Drop for MutexGuard<'a, T> {
#[inline(always)]
fn drop(&mut self) {
self.lock.lock.store(false, Release);
}
}