Skip to content

Commit

Permalink
core: Make Debug impl of raw pointers print metadata if present
Browse files Browse the repository at this point in the history
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>
  • Loading branch information
Enselic and lukas-code committed Feb 13, 2025
1 parent 5f086cc commit b772f99
Show file tree
Hide file tree
Showing 3 changed files with 15 additions and 6 deletions.
11 changes: 10 additions & 1 deletion library/core/src/fmt/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2773,10 +2773,19 @@ impl Display for char {
}
}

use core::any::TypeId;

#[stable(feature = "rust1", since = "1.0.0")]
impl<T: ?Sized> Pointer for *const T {
fn fmt(&self, f: &mut Formatter<'_>) -> Result {
pointer_fmt_inner(self.expose_provenance(), f)
if TypeId::of::<<T as core::ptr::Pointee>::Metadata>() == TypeId::of::<()>() {
pointer_fmt_inner(self.expose_provenance(), f)
} else {
f.debug_struct("Pointer")
.field_with("addr", |f| pointer_fmt_inner(self.expose_provenance(), f))
.field("metadata", &core::ptr::metadata(*self))
.finish()
}
}
}

Expand Down
2 changes: 1 addition & 1 deletion library/core/src/ptr/metadata.rs
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ pub trait Pointee {
// NOTE: Keep trait bounds in `static_assert_expected_bounds_for_metadata`
// in `library/core/src/ptr/metadata.rs`
// in sync with those here:
type Metadata: fmt::Debug + Copy + Send + Sync + Ord + Hash + Unpin + Freeze;
type Metadata: fmt::Debug + Copy + Send + Sync + Ord + Hash + Unpin + Freeze + 'static;
}

/// Pointers to types implementing this trait alias are “thin”.
Expand Down
8 changes: 4 additions & 4 deletions library/coretests/tests/fmt/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -42,12 +42,12 @@ fn test_fmt_debug_of_raw_pointers() {
check_fmt(plain as *const i32, "$HEX");

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

let vtable = &mut 500 as &mut dyn Debug;
check_fmt(vtable as *mut dyn Debug, "$HEX");
check_fmt(vtable as *const dyn Debug, "$HEX");
check_fmt(vtable as *mut dyn Debug, "Pointer { addr: $HEX, metadata: DynMetadata($HEX) }");
check_fmt(vtable as *const dyn Debug, "Pointer { addr: $HEX, metadata: DynMetadata($HEX) }");
}

#[test]
Expand Down

0 comments on commit b772f99

Please sign in to comment.