sync: better Debug for Mutex (#2725)

This commit is contained in:
Mikail Bagishov
2020-07-31 21:00:23 +02:00
committed by GitHub
parent 646fbae765
commit 8fda719845
2 changed files with 23 additions and 1 deletions
+14 -1
View File
@@ -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>,
@@ -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> {
+9
View File
@@ -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> }"#)
}