//! Implementation of a critical section based mutex that also implements the `mutex-trait`. //! //! ## Safety //! //! Note that this is only safe in single core applications. use core::cell::UnsafeCell; /// A critical section based mutex. pub struct CriticalSectionMutex { data: UnsafeCell, } impl CriticalSectionMutex { /// Create a new mutex pub const fn new(data: T) -> Self { CriticalSectionMutex { data: UnsafeCell::new(data), } } } impl mutex_trait::Mutex for &'_ CriticalSectionMutex { type Data = T; fn lock(&mut self, f: impl FnOnce(&mut Self::Data) -> R) -> R { crate::interrupt::free(|_| f(unsafe { &mut *self.data.get() })) } } // NOTE A `Mutex` can be used as a channel so the protected data must be `Send` // to prevent sending non-Sendable stuff (e.g. access tokens) across different // execution contexts (e.g. interrupts) unsafe impl Sync for CriticalSectionMutex where T: Send {}