use std::cell::{Cell, RefCell};
use std::rc::Rc;
use std::thread::LocalKey;
type Slot<A, R> = Option<(Rc<Cell<bool>>, Box<dyn FnOnce(A) -> R>)>;
pub(crate) struct OneShotHook<A = (), R = ()> {
slot: RefCell<Slot<A, R>>,
}
impl<A, R> OneShotHook<A, R> {
pub(crate) const fn new() -> Self {
Self {
slot: RefCell::new(None),
}
}
}
pub(crate) fn arm(key: &'static LocalKey<OneShotHook>, hook: impl FnOnce() + 'static) -> Armed {
arm_with(key, move |()| hook())
}
pub(crate) fn arm_with<A: 'static, R: 'static>(
key: &'static LocalKey<OneShotHook<A, R>>,
hook: impl FnOnce(A) -> R + 'static,
) -> Armed<A, R> {
let fired = Rc::new(Cell::new(false));
key.with(|h| {
let previous = h.slot.borrow_mut().replace((Rc::clone(&fired), Box::new(hook)));
debug_assert!(previous.is_none(), "a one-shot hook is already armed");
});
Armed { key, fired }
}
pub(crate) fn fire(key: &'static LocalKey<OneShotHook>) {
fire_with(key, ());
}
pub(crate) fn fire_with<A: 'static, R: 'static>(key: &'static LocalKey<OneShotHook<A, R>>, arg: A) -> Option<R> {
let taken = key.with(|h| h.slot.borrow_mut().take());
taken.map(|(fired, hook)| {
fired.set(true);
hook(arg)
})
}
#[must_use = "dropping this immediately clears the armed hook; bind it for the scope that needs it"]
pub(crate) struct Armed<A: 'static = (), R: 'static = ()> {
key: &'static LocalKey<OneShotHook<A, R>>,
fired: Rc<Cell<bool>>,
}
impl<A: 'static, R: 'static> Armed<A, R> {
#[track_caller]
pub(crate) fn assert_fired(&self) {
assert!(
self.fired.get(),
"the armed one-shot hook never fired: its fire point was not reached"
);
}
}
impl<A: 'static, R: 'static> Drop for Armed<A, R> {
fn drop(&mut self) {
let mine = self.key.with(|h| {
let mut slot = h.slot.borrow_mut();
match &*slot {
Some((fired, _)) if Rc::ptr_eq(fired, &self.fired) => slot.take(),
_ => None,
}
});
drop(mine);
}
}
#[cfg(test)]
#[path = "oneshot_hook_tests.rs"]
mod oneshot_hook_tests;