diff --git a/tokio/src/sync/mutex.rs b/tokio/src/sync/mutex.rs index 642058be626..df348457fec 100644 --- a/tokio/src/sync/mutex.rs +++ b/tokio/src/sync/mutex.rs @@ -115,7 +115,6 @@ use std::sync::Arc; /// [`std::sync::Mutex`]: struct@std::sync::Mutex /// [`Send`]: trait@std::marker::Send /// [`lock`]: method@Mutex::lock -#[derive(Debug)] pub struct Mutex { s: semaphore::Semaphore, c: UnsafeCell, @@ -373,6 +372,20 @@ where } } +impl std::fmt::Debug for Mutex +where + T: std::fmt::Debug, +{ + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + let mut d = f.debug_struct("Mutex"); + match self.try_lock() { + Ok(inner) => d.field("data", &*inner), + Err(_) => d.field("data", &format_args!("")), + }; + d.finish() + } +} + // === impl MutexGuard === impl Drop for MutexGuard<'_, T> { diff --git a/tokio/tests/sync_mutex.rs b/tokio/tests/sync_mutex.rs index 444ebd6a22d..96194b31d9d 100644 --- a/tokio/tests/sync_mutex.rs +++ b/tokio/tests/sync_mutex.rs @@ -152,3 +152,12 @@ async fn debug_format() { let m = Mutex::new(s.to_string()); assert_eq!(format!("{:?}", s), format!("{:?}", m.lock().await)); } + +#[tokio::test] +async fn mutex_debug() { + let s = "data"; + let m = Mutex::new(s.to_string()); + assert_eq!(format!("{:?}", m), r#"Mutex { data: "data" }"#); + let _guard = m.lock().await; + assert_eq!(format!("{:?}", m), r#"Mutex { data: }"#) +}