#[cfg(feature = "unwind")]
use alloc::string::String;
pub fn panic_hook() {
std::panic::set_hook(alloc::boxed::Box::new(on_panic));
}
#[cfg(not(all(feature = "unwind", panic = "unwind")))]
fn on_panic(info: &std::panic::PanicHookInfo) {
crate::panic_report(info)
}
#[cfg(all(feature = "unwind", panic = "unwind"))]
const NOUNWIND: [&str; 2] = ["panic in a function that cannot unwind", "panic in a destructor during cleanup"];
#[cfg(all(feature = "unwind", panic = "unwind"))]
fn on_panic(info: &std::panic::PanicHookInfo) {
if info.payload_as_str().is_some_and(|m| NOUNWIND.contains(&m)) {
report_last(None, info) }
let text = alloc::format!("{info}");
let _ = LAST.try_with(|l| l.try_borrow_mut().map(|mut s| *s = Some(text)));
}
#[cfg(feature = "unwind")]
std::thread_local! {
static LAST: core::cell::RefCell<Option<String>> = const { core::cell::RefCell::new(None) };
}
#[cfg(feature = "unwind")]
fn report_last(message: Option<&str>, now: &dyn core::fmt::Display) -> ! {
let last = LAST.try_with(|l| l.try_borrow_mut().ok().and_then(|mut s| s.take())).ok().flatten();
match last {
Some(text) if message.is_none_or(|m| text.ends_with(m)) => crate::panic_report(&text),
_ => crate::panic_report(now),
}
}
#[cfg(feature = "unwind")]
pub fn abort_on_unwind<R>(f: impl FnOnce() -> R) -> R {
match std::panic::catch_unwind(std::panic::AssertUnwindSafe(f)) {
Ok(r) => r,
Err(payload) => {
let message = payload.downcast_ref::<&str>().copied().or_else(|| payload.downcast_ref::<String>().map(|s| s.as_str()));
report_last(message, &message.unwrap_or("panicked (no message)"))
}
}
}
#[cfg(feature = "unwind")]
pub fn panic_take() -> Option<String> {
LAST.try_with(|l| l.try_borrow_mut().ok().and_then(|mut s| s.take())).ok().flatten()
}