Skip to content

Commit

Permalink
Try to write the panic message with a single write_all call
Browse files Browse the repository at this point in the history
  • Loading branch information
Zoxc authored and gitbot committed Feb 20, 2025
1 parent 2e008d6 commit fa7a493
Showing 1 changed file with 17 additions and 1 deletion.
18 changes: 17 additions & 1 deletion std/src/panicking.rs
Original file line number Diff line number Diff line change
Expand Up @@ -266,7 +266,23 @@ fn default_hook(info: &PanicHookInfo<'_>) {
// Use a lock to prevent mixed output in multithreading context.
// Some platforms also require it when printing a backtrace, like `SymFromAddr` on Windows.
let mut lock = backtrace::lock();
let _ = writeln!(err, "thread '{name}' panicked at {location}:\n{msg}");
// Try to write the panic message to a buffer first to prevent other concurrent outputs
// interleaving with it.
let mut buffer = [0u8; 512];
let mut cursor = crate::io::Cursor::new(&mut buffer[..]);

let write_msg = |dst: &mut dyn crate::io::Write| {
// We add a newline to ensure the panic message appears at the start of a line.
writeln!(dst, "\nthread '{name}' panicked at {location}:\n{msg}")
};

if write_msg(&mut cursor).is_ok() {
let pos = cursor.position() as usize;
let _ = err.write_all(&buffer[0..pos]);
} else {
// The message did not fit into the buffer, write it directly instead.
let _ = write_msg(err);
};

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

Expand Down

0 comments on commit fa7a493

Please sign in to comment.