ktrs_syntax/
caught_panic.rs1use std::cell::Cell;
6use std::panic::{self, AssertUnwindSafe};
7use std::sync::Once;
8
9thread_local! {
10 static CATCHING: Cell<bool> = const { Cell::new(false) };
11}
12
13pub fn catch_quietly<R>(f: impl FnOnce() -> R) -> std::thread::Result<R> {
15 let outer = CATCHING.replace(true);
16 let result = panic::catch_unwind(AssertUnwindSafe(f));
17 CATCHING.set(outer);
18 result
19}
20
21pub fn silence_caught_panics() {
24 static INSTALL: Once = Once::new();
25 INSTALL.call_once(|| {
26 let previous = panic::take_hook();
27 panic::set_hook(Box::new(move |info| {
28 if !CATCHING.get() {
29 previous(info);
30 }
31 }));
32 });
33}