Skip to content

Commit 4c641b1

Browse files
Enseliclukas-code
andcommitted
core: Make Debug impl of raw pointers print metadata if present
Make Rust pointers less magic by including metadata information in their `Debug` output. This does not break Rust stability guarantees because `Debug` output is explicitly exempted from stability: https://doc.rust-lang.org/std/fmt/trait.Debug.html#stability Co-authored-by: Lukas <26522220+lukas-code@users.noreply.github.com>
1 parent f6c5528 commit 4c641b1

File tree

2 files changed

+12
-5
lines changed

2 files changed

+12
-5
lines changed

Diff for: library/core/src/fmt/mod.rs

+8-1
Original file line numberDiff line numberDiff line change
@@ -2767,7 +2767,14 @@ impl Display for char {
27672767
#[stable(feature = "rust1", since = "1.0.0")]
27682768
impl<T: ?Sized> Pointer for *const T {
27692769
fn fmt(&self, f: &mut Formatter<'_>) -> Result {
2770-
pointer_fmt_inner(self.expose_provenance(), f)
2770+
if core::mem::size_of::<<T as core::ptr::Pointee>::Metadata>() == 0 {
2771+
pointer_fmt_inner(self.expose_provenance(), f)
2772+
} else {
2773+
f.debug_struct("Pointer")
2774+
.field_with("addr", |f| pointer_fmt_inner(self.expose_provenance(), f))
2775+
.field("metadata", &core::ptr::metadata(*self))
2776+
.finish()
2777+
}
27712778
}
27722779
}
27732780

Diff for: library/core/tests/fmt/mod.rs

+4-4
Original file line numberDiff line numberDiff line change
@@ -42,12 +42,12 @@ fn test_fmt_debug_of_raw_pointers() {
4242
check_fmt(plain as *const i32, "$HEX");
4343

4444
let slice = &mut [200, 300, 400][..];
45-
check_fmt(slice as *mut [i32], "$HEX");
46-
check_fmt(slice as *const [i32], "$HEX");
45+
check_fmt(slice as *mut [i32], "Pointer { addr: $HEX, metadata: 3 }");
46+
check_fmt(slice as *const [i32], "Pointer { addr: $HEX, metadata: 3 }");
4747

4848
let vtable = &mut 500 as &mut dyn Debug;
49-
check_fmt(vtable as *mut dyn Debug, "$HEX");
50-
check_fmt(vtable as *const dyn Debug, "$HEX");
49+
check_fmt(vtable as *mut dyn Debug, "Pointer { addr: $HEX, metadata: DynMetadata($HEX) }");
50+
check_fmt(vtable as *const dyn Debug, "Pointer { addr: $HEX, metadata: DynMetadata($HEX) }");
5151
}
5252

5353
#[test]

0 commit comments

Comments
 (0)