From cc4ff9ef2d7b0a6a68e98cd3aa08855677ed8b90 Mon Sep 17 00:00:00 2001 From: W Etheredge <me@wetheredge.com> Date: Sun, 5 May 2024 23:10:00 -0500 Subject: [PATCH] embassy_sync::Mutex: Implement traits to match std --- embassy-sync/src/mutex.rs | 78 ++++++++++++++++++++++++++++++++++++++- 1 file changed, 77 insertions(+), 1 deletion(-) diff --git a/embassy-sync/src/mutex.rs b/embassy-sync/src/mutex.rs index b48a408c4..8c3a3af9f 100644 --- a/embassy-sync/src/mutex.rs +++ b/embassy-sync/src/mutex.rs @@ -3,9 +3,9 @@ //! This module provides a mutex that can be used to synchronize data between asynchronous tasks. use core::cell::{RefCell, UnsafeCell}; use core::future::poll_fn; -use core::mem; use core::ops::{Deref, DerefMut}; use core::task::Poll; +use core::{fmt, mem}; use crate::blocking_mutex::raw::RawMutex; use crate::blocking_mutex::Mutex as BlockingMutex; @@ -129,6 +129,42 @@ where } } +impl<M: RawMutex, T> From<T> for Mutex<M, T> { + fn from(from: T) -> Self { + Self::new(from) + } +} + +impl<M, T> Default for Mutex<M, T> +where + M: RawMutex, + T: ?Sized + Default, +{ + fn default() -> Self { + Self::new(Default::default()) + } +} + +impl<M, T> fmt::Debug for Mutex<M, T> +where + M: RawMutex, + T: ?Sized + fmt::Debug, +{ + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + let mut d = f.debug_struct("Mutex"); + match self.try_lock() { + Ok(value) => { + d.field("inner", &&*value); + } + Err(TryLockError) => { + d.field("inner", &format_args!("<locked>")); + } + } + + d.finish_non_exhaustive() + } +} + /// Async mutex guard. /// /// Owning an instance of this type indicates having @@ -202,6 +238,26 @@ where } } +impl<'a, M, T> fmt::Debug for MutexGuard<'a, M, T> +where + M: RawMutex, + T: ?Sized + fmt::Debug, +{ + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + fmt::Debug::fmt(&**self, f) + } +} + +impl<'a, M, T> fmt::Display for MutexGuard<'a, M, T> +where + M: RawMutex, + T: ?Sized + fmt::Display, +{ + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + fmt::Display::fmt(&**self, f) + } +} + /// A handle to a held `Mutex` that has had a function applied to it via [`MutexGuard::map`] or /// [`MappedMutexGuard::map`]. /// @@ -285,6 +341,26 @@ where { } +impl<'a, M, T> fmt::Debug for MappedMutexGuard<'a, M, T> +where + M: RawMutex, + T: ?Sized + fmt::Debug, +{ + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + fmt::Debug::fmt(&**self, f) + } +} + +impl<'a, M, T> fmt::Display for MappedMutexGuard<'a, M, T> +where + M: RawMutex, + T: ?Sized + fmt::Display, +{ + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + fmt::Display::fmt(&**self, f) + } +} + #[cfg(test)] mod tests { use crate::blocking_mutex::raw::NoopRawMutex;