use std::cell::Cell;
pub type Guard = fn(&'static str, &mut dyn FnMut());
thread_local! {
static GUARD: Cell<Option<Guard>> = const { Cell::new(None) };
}
pub fn set_guard(guard: Guard) {
GUARD.with(|g| g.set(Some(guard)));
}
pub fn guarded<R>(place: &'static str, fallback: R, f: impl FnOnce() -> R) -> R {
let Some(guard) = GUARD.try_with(Cell::get).ok().flatten() else { return f() };
let (mut f, mut out) = (Some(f), None);
guard(place, &mut || {
if let Some(f) = f.take() {
out = Some(f());
}
});
out.unwrap_or(fallback)
}