Skip to content

Commit

Permalink
sync: better Debug for Mutex (#2725)
Browse files Browse the repository at this point in the history
  • Loading branch information
MikailBag authored Jul 31, 2020
1 parent 646fbae commit 8fda719
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 1 deletion.
15 changes: 14 additions & 1 deletion tokio/src/sync/mutex.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<T: ?Sized> {
s: semaphore::Semaphore,
c: UnsafeCell<T>,
Expand Down Expand Up @@ -373,6 +372,20 @@ where
}
}

impl<T> std::fmt::Debug for Mutex<T>
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!("<locked>")),
};
d.finish()
}
}

// === impl MutexGuard ===

impl<T: ?Sized> Drop for MutexGuard<'_, T> {
Expand Down
9 changes: 9 additions & 0 deletions tokio/tests/sync_mutex.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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: <locked> }"#)
}

0 comments on commit 8fda719

Please sign in to comment.