use std::cell::{Cell, RefCell};
use std::thread::LocalKey;
type Slot = Option<(u64, Box<dyn FnOnce()>)>;
pub(crate) struct OneShotHook {
slot: RefCell<Slot>,
generation: Cell<u64>,
}
impl OneShotHook {
pub(crate) const fn new() -> Self {
Self {
slot: RefCell::new(None),
generation: Cell::new(0),
}
}
}
pub(crate) fn arm(key: &'static LocalKey<OneShotHook>, hook: impl FnOnce() + 'static) -> Armed {
let generation = key.with(|h| {
let generation = h.generation.get() + 1;
h.generation.set(generation);
let previous = h.slot.borrow_mut().replace((generation, Box::new(hook)));
debug_assert!(previous.is_none(), "a one-shot hook is already armed");
generation
});
Armed { key, generation }
}
pub(crate) fn fire(key: &'static LocalKey<OneShotHook>) {
let taken = key.with(|h| h.slot.borrow_mut().take());
if let Some((_, hook)) = taken {
hook();
}
}
#[must_use = "dropping this immediately clears the armed hook; bind it for the scope that needs it"]
pub(crate) struct Armed {
key: &'static LocalKey<OneShotHook>,
generation: u64,
}
impl Drop for Armed {
fn drop(&mut self) {
let mine = self.key.with(|h| {
let mut slot = h.slot.borrow_mut();
match &*slot {
Some((generation, _)) if *generation == self.generation => slot.take(),
_ => None,
}
});
drop(mine);
}
}
#[cfg(test)]
#[path = "oneshot_hook_tests.rs"]
mod oneshot_hook_tests;