File tree Expand file tree Collapse file tree 1 file changed +17
-1
lines changed Expand file tree Collapse file tree 1 file changed +17
-1
lines changed Original file line number Diff line number Diff 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, "\n thread '{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
You can’t perform that action at this time.
0 commit comments