mirror of
https://github.com/tokio-rs/tokio.git
synced 2026-08-23 00:00:10 +02:00
sync: better Debug for Mutex (#2725)
This commit is contained in:
+14
-1
@@ -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> {
|
||||
|
||||
@@ -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> }"#)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user