pub trait PortMutex {
type Port;
fn create(v: Self::Port) -> Self;
fn lock<R, F: FnOnce(&mut Self::Port) -> R>(&self, f: F) -> R;
}
impl<T> PortMutex for core::cell::RefCell<T> {
type Port = T;
fn create(v: Self::Port) -> Self {
core::cell::RefCell::new(v)
}
fn lock<R, F: FnOnce(&mut Self::Port) -> R>(&self, f: F) -> R {
let mut v = self.borrow_mut();
f(&mut v)
}
}
#[cfg(any(test, feature = "std"))]
impl<T> PortMutex for std::sync::Mutex<T> {
type Port = T;
fn create(v: Self::Port) -> Self {
std::sync::Mutex::new(v)
}
fn lock<R, F: FnOnce(&mut Self::Port) -> R>(&self, f: F) -> R {
let mut v = self.lock().unwrap();
f(&mut v)
}
}
#[cfg(feature = "critical-section")]
impl<T> PortMutex for critical_section::Mutex<core::cell::RefCell<T>> {
type Port = T;
fn create(v: Self::Port) -> Self {
critical_section::Mutex::new(core::cell::RefCell::new(v))
}
fn lock<R, F: FnOnce(&mut Self::Port) -> R>(&self, f: F) -> R {
critical_section::with(|cs| {
let mut v = self.borrow_ref_mut(cs);
f(&mut v)
})
}
}