use core::cell::UnsafeCell;
pub struct Mutex<T> {
data: UnsafeCell<T>,
}
unsafe impl<T> Send for Mutex<T> {}
unsafe impl<T> Sync for Mutex<T> {}
impl<T> Mutex<T> {
pub fn new(val: T) -> Self {
Self {
data: UnsafeCell::new(val),
}
}
pub fn lock(&self) -> Result<MutexGuard<'_, T>, ()> {
Ok(MutexGuard { mutex: self })
}
}
pub struct MutexGuard<'a, T> {
mutex: &'a Mutex<T>,
}
impl<T> core::ops::Deref for MutexGuard<'_, T> {
type Target = T;
fn deref(&self) -> &T {
unsafe { &*self.mutex.data.get() }
}
}
impl<T> core::ops::DerefMut for MutexGuard<'_, T> {
fn deref_mut(&mut self) -> &mut T {
unsafe { &mut *self.mutex.data.get() }
}
}