Skip to content

Commit a2b498b

Browse files
Zoxcgitbot
authored and
gitbot
committed
Try to write the panic message with a single write_all call
1 parent a222c95 commit a2b498b

File tree

1 file changed

+17
-1
lines changed

1 file changed

+17
-1
lines changed

std/src/panicking.rs

+17-1
Original file line numberDiff line numberDiff line change
@@ -266,7 +266,23 @@ fn default_hook(info: &PanicHookInfo<'_>) {
266266
// Use a lock to prevent mixed output in multithreading context.
267267
// Some platforms also require it when printing a backtrace, like `SymFromAddr` on Windows.
268268
let mut lock = backtrace::lock();
269-
let _ = writeln!(err, "thread '{name}' panicked at {location}:\n{msg}");
269+
// Try to write the panic message to a buffer first to prevent other concurrent outputs
270+
// interleaving with it.
271+
let mut buffer = [0u8; 512];
272+
let mut cursor = crate::io::Cursor::new(&mut buffer[..]);
273+
274+
let write_msg = |dst: &mut dyn crate::io::Write| {
275+
// We add a newline to ensure the panic message appears at the start of a line.
276+
writeln!(dst, "\nthread '{name}' panicked at {location}:\n{msg}")
277+
};
278+
279+
if write_msg(&mut cursor).is_ok() {
280+
let pos = cursor.position() as usize;
281+
let _ = err.write_all(&buffer[0..pos]);
282+
} else {
283+
// The message did not fit into the buffer, write it directly instead.
284+
let _ = write_msg(err);
285+
};
270286

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

0 commit comments

Comments
 (0)