1#![no_std]
2
3use core::fmt::Write;
4use core::marker::PhantomPinned;
5use core::mem::{transmute, MaybeUninit};
6use core::ops::DerefMut;
7use core::panic::PanicInfo;
8use core::pin::Pin;
9use core::ptr::null_mut;
10
11static mut PANIC_HANDLER_GETTER: Option<unsafe fn(handler: *mut (), info: &PanicInfo)> = None;
12static mut PANIC_HANDLER: *mut () = null_mut();
13
14unsafe fn trampoline<W: Write>(ptr: *mut (), info: &PanicInfo) {
16 let handler: &mut PanicHandler<W> = transmute(ptr);
17
18 let _ = write!(handler.deref_mut(), "{}", info);
19}
20
21pub struct PanicHandler<W: Write> {
22 writer: MaybeUninit<W>,
23 _pin: PhantomPinned,
24}
25
26impl<W: Write> PanicHandler<W> {
27 #[must_use = "the panic handler must be kept in scope"]
35 pub fn new(writer: W) -> Pin<Self> {
36 let handler = unsafe {
37 Pin::new_unchecked(PanicHandler {
38 writer: MaybeUninit::new(writer),
39 _pin: PhantomPinned,
40 })
41 };
42 unsafe {
43 PANIC_HANDLER_GETTER = Some(trampoline::<W>);
44 PANIC_HANDLER = transmute(&handler);
45 }
46 handler
47 }
48
49 pub fn detach(handler: Pin<Self>) -> W {
51 unsafe {
52 PANIC_HANDLER_GETTER = None;
53 PANIC_HANDLER = null_mut();
54
55 let mut handler = Pin::into_inner_unchecked(handler);
57 let writer = core::mem::replace(&mut handler.writer, MaybeUninit::uninit());
58
59 writer.assume_init()
61 }
62 }
63}
64
65impl<W: Write> Drop for PanicHandler<W> {
66 fn drop(&mut self) {
67 unsafe {
68 PANIC_HANDLER_GETTER = None;
69 PANIC_HANDLER = null_mut();
70 }
71 }
72}
73
74impl<W: Write> core::ops::Deref for PanicHandler<W> {
75 type Target = W;
76
77 fn deref(&self) -> &Self::Target {
78 unsafe { &*self.writer.as_ptr() }
80 }
81}
82
83impl<W: Write> core::ops::DerefMut for PanicHandler<W> {
84 fn deref_mut(&mut self) -> &mut Self::Target {
85 unsafe { &mut *self.writer.as_mut_ptr() }
87 }
88}
89
90#[panic_handler]
91fn panic(info: &PanicInfo) -> ! {
92 unsafe {
93 if let Some(trampoline) = PANIC_HANDLER_GETTER {
94 trampoline(PANIC_HANDLER, info);
95 }
96 }
97 loop {}
98}