use core::cell::UnsafeCell;
use core::sync::atomic::{self, AtomicBool};
use core::ops;
use shim;
pub struct Mutex<T> {
inner: UnsafeCell<T>,
locked: AtomicBool,
}
impl<T> Mutex<T> {
#[inline]
pub const fn new(inner: T) -> Mutex<T> {
Mutex {
inner: UnsafeCell::new(inner),
locked: AtomicBool::new(false),
}
}
#[inline]
pub fn lock(&self) -> MutexGuard<T> {
#[cfg(not(feature = "unsafe_no_mutex_lock"))]
while self.locked.compare_and_swap(false, true, atomic::Ordering::SeqCst) {
shim::syscalls::sched_yield();
}
MutexGuard {
mutex: self,
}
}
}
#[must_use]
pub struct MutexGuard<'a, T: 'a> {
mutex: &'a Mutex<T>,
}
impl<'a, T> Drop for MutexGuard<'a, T> {
#[inline]
fn drop(&mut self) {
self.mutex.locked.store(false, atomic::Ordering::SeqCst);
}
}
impl<'a, T> ops::Deref for MutexGuard<'a, T> {
type Target = T;
#[inline]
fn deref(&self) -> &T {
unsafe {
&*self.mutex.inner.get()
}
}
}
impl<'a, T> ops::DerefMut for MutexGuard<'a, T> {
fn deref_mut(&mut self) -> &mut T {
unsafe {
&mut *self.mutex.inner.get()
}
}
}
unsafe impl<T: Send> Send for Mutex<T> {}
unsafe impl<T: Send> Sync for Mutex<T> {}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_mutex() {
let mutex = Mutex::new(3);
assert_eq!(*mutex.lock(), 3);
*mutex.lock() = 4;
assert_eq!(*mutex.lock(), 4);
*mutex.lock() = 0xFF;
assert_eq!(*mutex.lock(), 0xFF);
}
}