Skip to content

Commit c1707aa

Browse files
committed
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<u32>, pub d: MaybeUninit<String>, } Prints as: Foo { a: 0, b: "hello", c: core::mem::maybe_uninit::MaybeUninit<u32>, d: core::mem::maybe_uninit::MaybeUninit<alloc::string::String>, } 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<u32>, d: MaybeUninit<alloc::string::String>, }
1 parent 318f96a commit c1707aa

File tree

2 files changed

+12
-1
lines changed

2 files changed

+12
-1
lines changed

library/core/src/mem/maybe_uninit.rs

+5-1
Original file line numberDiff line numberDiff line change
@@ -255,7 +255,11 @@ impl<T: Copy> Clone for MaybeUninit<T> {
255255
#[stable(feature = "maybe_uninit_debug", since = "1.41.0")]
256256
impl<T> fmt::Debug for MaybeUninit<T> {
257257
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
258-
f.pad(type_name::<Self>())
258+
// NB: there is no `.pad_fmt` so we can't use a simpler `format_args!("MaybeUninit<{..}>").
259+
// This needs to be adjusted if `MaybeUninit` moves modules.
260+
let full_name = type_name::<Self>();
261+
let short_name = full_name.split_once("mem::maybe_uninit::").unwrap().1;
262+
f.pad(short_name)
259263
}
260264
}
261265

library/core/tests/fmt/mod.rs

+7
Original file line numberDiff line numberDiff line change
@@ -43,3 +43,10 @@ fn pad_integral_resets() {
4343

4444
assert_eq!(format!("{Bar:<03}"), "1 0051 ");
4545
}
46+
47+
#[test]
48+
fn test_maybe_uninit_short() {
49+
// Ensure that the trimmed `MaybeUninit` Debug implementation doesn't break
50+
let x = core::mem::MaybeUninit::new(0u32);
51+
assert_eq!(format!("{x:?}"), "MaybeUninit<u32>");
52+
}

0 commit comments

Comments
 (0)