embassy/blocking_mutex: add MutexKind to allow writing code generic over mutex kinds.

This commit is contained in:
Dario Nieuwenhuis 2021-09-12 23:27:13 +02:00
parent e1f9dd1170
commit 5be5bdfd20
2 changed files with 25 additions and 4 deletions

View file

@ -0,0 +1,19 @@
use super::{CriticalSectionMutex, Mutex, NoopMutex, ThreadModeMutex};
pub trait MutexKind {
type Mutex<T>: Mutex<Data = T>;
}
pub enum CriticalSection {}
impl MutexKind for CriticalSection {
type Mutex<T> = CriticalSectionMutex<T>;
}
pub enum ThreadMode {}
impl MutexKind for ThreadMode {
type Mutex<T> = ThreadModeMutex<T>;
}
pub enum Noop {}
impl MutexKind for Noop {
type Mutex<T> = NoopMutex<T>;
}

View file

@ -1,5 +1,7 @@
//! Blocking mutex (not async)
pub mod kind;
use core::cell::UnsafeCell;
use critical_section::CriticalSection;
@ -13,7 +15,7 @@ pub trait Mutex {
fn new(data: Self::Data) -> Self;
/// Creates a critical section and grants temporary access to the protected data.
fn lock<R>(&mut self, f: impl FnOnce(&Self::Data) -> R) -> R;
fn lock<R>(&self, f: impl FnOnce(&Self::Data) -> R) -> R;
}
/// A "mutex" based on critical sections
@ -55,7 +57,7 @@ impl<T> Mutex for CriticalSectionMutex<T> {
Self::new(data)
}
fn lock<R>(&mut self, f: impl FnOnce(&Self::Data) -> R) -> R {
fn lock<R>(&self, f: impl FnOnce(&Self::Data) -> R) -> R {
critical_section::with(|cs| f(self.borrow(cs)))
}
}
@ -102,7 +104,7 @@ impl<T> Mutex for ThreadModeMutex<T> {
Self::new(data)
}
fn lock<R>(&mut self, f: impl FnOnce(&Self::Data) -> R) -> R {
fn lock<R>(&self, f: impl FnOnce(&Self::Data) -> R) -> R {
f(self.borrow())
}
}
@ -155,7 +157,7 @@ impl<T> Mutex for NoopMutex<T> {
Self::new(data)
}
fn lock<R>(&mut self, f: impl FnOnce(&Self::Data) -> R) -> R {
fn lock<R>(&self, f: impl FnOnce(&Self::Data) -> R) -> R {
f(self.borrow())
}
}