use core::cell::UnsafeCell;
pub struct Mutex<T> {
inner: UnsafeCell<T>,
}
impl<T> Mutex<T> {
pub const fn new(value: T) -> Self {
Mutex { inner: UnsafeCell::new(value) }
}
}
impl<T> Mutex<T> {
pub fn lock<F, R>(&self, f: F) -> R
where F: FnOnce(&mut T) -> R
{
unsafe { ::interrupt::free(|| f(&mut *self.inner.get())) }
}
}
unsafe impl<T> Sync for Mutex<T> {}
#[inline(always)]
pub unsafe fn disable() {
match () {
#[cfg(target_arch = "arm")]
() => {
asm!("cpsid i" :::: "volatile");
}
#[cfg(not(target_arch = "arm"))]
() => {}
}
}
#[inline(always)]
pub unsafe fn enable() {
match () {
#[cfg(target_arch = "arm")]
() => {
asm!("cpsie i" :::: "volatile");
}
#[cfg(not(target_arch = "arm"))]
() => {}
}
}
pub unsafe fn free<F, R>(f: F) -> R
where F: FnOnce() -> R
{
let primask = ::register::primask::read();
disable();
let r = f();
if primask & 1 == 0 {
enable();
}
r
}