Skip to content

Commit

Permalink
Ensure panic! messages are only formatted once
Browse files Browse the repository at this point in the history
  • Loading branch information
Amanieu committed Oct 2, 2023
1 parent 98d7379 commit 3a6ff98
Showing 1 changed file with 13 additions and 13 deletions.
26 changes: 13 additions & 13 deletions library/std/src/panicking.rs
Original file line number Diff line number Diff line change
Expand Up @@ -252,20 252,20 @@ fn default_hook(info: &PanicInfo<'_>) {
let name = thread.as_ref().and_then(|t| t.name()).unwrap_or("<unnamed>");

let write = |err: &mut dyn crate::io::Write| {
// Use the panic message directly if available, otherwise take it from
// the payload.
if let Some(msg) = info.message() {
let _ = writeln!(err, "thread '{name}' panicked at {location}:\n{msg}");
// The std panic runtime always sets a `&str` or `String` payload for `panic!` and related
// macros with the formatted message.
// We try using the payload first to avoid formatting the message twice.
let msg: &dyn fmt::Display = if let Some(s) = info.payload().downcast_ref::<&'static str>()
{
s
} else if let Some(s) = info.payload().downcast_ref::<String>() {
s
} else if let Some(msg) = info.message() {
msg
} else {
let msg = if let Some(s) = info.payload().downcast_ref::<&'static str>() {
*s
} else if let Some(s) = info.payload().downcast_ref::<String>() {
&s[..]
} else {
"Box<dyn Any>"
};
let _ = writeln!(err, "thread '{name}' panicked at {location}:\n{msg}");
}
&"Box<dyn Any>"
};
let _ = writeln!(err, "thread '{name}' panicked at {location}:\n{msg}");

static FIRST_PANIC: AtomicBool = AtomicBool::new(true);

Expand Down

0 comments on commit 3a6ff98

Please sign in to comment.