From c1707aaf0b8da047db0c1e1d97c7fa6c3545672d Mon Sep 17 00:00:00 2001 From: Trevor Gross Date: Thu, 21 Nov 2024 03:46:59 -0500 Subject: [PATCH] Shorten the `MaybeUninit` `Debug` implementation Currently the `Debug` implementation for `MaybeUninit` winds up being pretty verbose. This struct: #[derive(Debug)] pub struct Foo { pub a: u32, pub b: &'static str, pub c: MaybeUninit, pub d: MaybeUninit, } Prints as: Foo { a: 0, b: "hello", c: core::mem::maybe_uninit::MaybeUninit, d: core::mem::maybe_uninit::MaybeUninit, } The goal is just to be a standin for content so the path prefix doesn't add any useful information. Change the implementation to trim `MaybeUninit`'s leading path, meaning the new result is now: Foo { a: 0, b: "hello", c: MaybeUninit, d: MaybeUninit, } --- library/core/src/mem/maybe_uninit.rs | 6 +++++- library/core/tests/fmt/mod.rs | 7 +++++++ 2 files changed, 12 insertions(+), 1 deletion(-) diff --git a/library/core/src/mem/maybe_uninit.rs b/library/core/src/mem/maybe_uninit.rs index 58315cb74f0a1..27273e4eedf3a 100644 --- a/library/core/src/mem/maybe_uninit.rs +++ b/library/core/src/mem/maybe_uninit.rs @@ -255,7 +255,11 @@ impl Clone for MaybeUninit { #[stable(feature = "maybe_uninit_debug", since = "1.41.0")] impl fmt::Debug for MaybeUninit { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - f.pad(type_name::()) + // NB: there is no `.pad_fmt` so we can't use a simpler `format_args!("MaybeUninit<{..}>"). + // This needs to be adjusted if `MaybeUninit` moves modules. + let full_name = type_name::(); + let short_name = full_name.split_once("mem::maybe_uninit::").unwrap().1; + f.pad(short_name) } } diff --git a/library/core/tests/fmt/mod.rs b/library/core/tests/fmt/mod.rs index 704d246139947..f7512abae3820 100644 --- a/library/core/tests/fmt/mod.rs +++ b/library/core/tests/fmt/mod.rs @@ -43,3 +43,10 @@ fn pad_integral_resets() { assert_eq!(format!("{Bar:<03}"), "1 0051 "); } + +#[test] +fn test_maybe_uninit_short() { + // Ensure that the trimmed `MaybeUninit` Debug implementation doesn't break + let x = core::mem::MaybeUninit::new(0u32); + assert_eq!(format!("{x:?}"), "MaybeUninit"); +}