use std::cell::Cell;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
#[derive(Clone, Debug, Default)]
pub struct ParseCancel(Arc<AtomicBool>);
thread_local! {
static INSTALLED: Cell<Option<ParseCancel>> = const { Cell::new(None) };
}
impl ParseCancel {
#[must_use]
pub fn new() -> Self {
Self::default()
}
pub fn cancel(&self) {
self.0.store(true, Ordering::Relaxed);
}
#[must_use]
pub fn is_cancelled(&self) -> bool {
self.0.load(Ordering::Relaxed)
}
pub fn run<T>(&self, f: impl FnOnce() -> T) -> T {
let previous = INSTALLED.try_with(|slot| slot.replace(Some(self.clone())));
let _restore = Restore(previous.ok().flatten());
f()
}
}
struct Restore(Option<ParseCancel>);
impl Drop for Restore {
fn drop(&mut self) {
let previous = self.0.take();
let _ = INSTALLED.try_with(|slot| slot.set(previous));
}
}
pub(crate) fn requested() -> bool {
INSTALLED
.try_with(|slot| {
let flag = slot.take();
let cancelled = flag.as_ref().is_some_and(ParseCancel::is_cancelled);
slot.set(flag);
cancelled
})
.unwrap_or(false)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_flag_counts_only_inside_its_run() {
let outer = ParseCancel::new();
let inner = ParseCancel::new();
inner.cancel();
assert!(!requested(), "nothing is installed yet");
outer.run(|| {
assert!(!requested(), "the outer flag is not cancelled");
inner.run(|| assert!(requested(), "the inner flag is"));
assert!(!requested(), "the outer flag is back");
outer.cancel();
assert!(requested(), "a cancel reaches the running closure");
});
assert!(!requested(), "nothing is installed after the run");
}
#[test]
fn a_cancel_reaches_a_clone_on_another_thread() {
let flag = ParseCancel::new();
let parsing = flag.clone();
let (cancelled, wait_for_cancel) = std::sync::mpsc::channel::<()>();
let seen = std::thread::spawn(move || {
parsing.run(|| {
wait_for_cancel
.recv()
.expect("the test thread reports the cancel");
requested()
})
});
flag.cancel();
cancelled
.send(())
.expect("the parsing thread waits for the report");
assert!(seen.join().expect("the parsing thread must not panic"));
}
}