From f3b9be7beede167295e8dc431e417bea77bb2455 Mon Sep 17 00:00:00 2001 From: Alexander van Saase Date: Wed, 19 Mar 2025 19:32:05 +0100 Subject: [PATCH 1/2] embassy-sync: add lock_mut to blocking_mutex::Mutex --- embassy-sync/src/blocking_mutex/mod.rs | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/embassy-sync/src/blocking_mutex/mod.rs b/embassy-sync/src/blocking_mutex/mod.rs index beafdb43d..5b0e4144a 100644 --- a/embassy-sync/src/blocking_mutex/mod.rs +++ b/embassy-sync/src/blocking_mutex/mod.rs @@ -50,6 +50,20 @@ impl Mutex { f(inner) }) } + + /// Creates a critical section and grants temporary mutable access to the protected data. + /// + /// # Safety + /// This method is unsafe because calling this method when the mutex is already locked, + /// either using this method or `lock`, violates Rust's aliasing rules. + pub unsafe fn lock_mut(&self, f: impl FnOnce(&mut T) -> U) -> U { + self.raw.lock(|| { + let ptr = self.data.get() as *mut T; + // Safety: we have exclusive access to the data, as long as this mutex is not locked re-entrantly + let inner = unsafe { &mut *ptr }; + f(inner) + }) + } } impl Mutex { From 7a031eed66ef27e83b8582e7c1e7ca00d16ccf64 Mon Sep 17 00:00:00 2001 From: Alexander van Saase Date: Fri, 21 Mar 2025 23:02:04 +0100 Subject: [PATCH 2/2] Add note about RefCell alternative --- embassy-sync/src/blocking_mutex/mod.rs | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/embassy-sync/src/blocking_mutex/mod.rs b/embassy-sync/src/blocking_mutex/mod.rs index 5b0e4144a..a41bc3569 100644 --- a/embassy-sync/src/blocking_mutex/mod.rs +++ b/embassy-sync/src/blocking_mutex/mod.rs @@ -54,8 +54,11 @@ impl Mutex { /// Creates a critical section and grants temporary mutable access to the protected data. /// /// # Safety - /// This method is unsafe because calling this method when the mutex is already locked, - /// either using this method or `lock`, violates Rust's aliasing rules. + /// + /// This method is marked unsafe because calling this method re-entrantly, i.e. within + /// another `lock_mut` or `lock` closure, violates Rust's aliasing rules. Calling this + /// method at the same time from different tasks is safe. For a safe alternative with + /// mutable access that never causes UB, use a `RefCell` in a `Mutex`. pub unsafe fn lock_mut(&self, f: impl FnOnce(&mut T) -> U) -> U { self.raw.lock(|| { let ptr = self.data.get() as *mut T;