use std::sync::{Arc, Mutex, MutexGuard, PoisonError, Weak};
use crate::notice::Notice;
#[derive(Clone, Debug, Default)]
pub struct Cancel(Arc<Mutex<Watched>>);
#[derive(Debug, Default)]
struct Watched {
cancelled: bool,
runs: Vec<Weak<Notice>>,
}
impl Cancel {
#[must_use]
pub fn new() -> Self {
Self::default()
}
pub fn cancel(&self) {
let mut watched = self.lock();
watched.cancelled = true;
for run in watched.runs.drain(..).filter_map(|run| run.upgrade()) {
run.set(|flags| flags.cancelled = true);
}
}
#[must_use]
pub fn is_cancelled(&self) -> bool {
self.lock().cancelled
}
pub(crate) fn watch(&self, notice: &Arc<Notice>) {
let mut watched = self.lock();
if watched.cancelled {
notice.set(|flags| flags.cancelled = true);
return;
}
watched.runs.retain(|run| run.strong_count() > 0);
watched.runs.push(Arc::downgrade(notice));
}
fn lock(&self) -> MutexGuard<'_, Watched> {
self.0.lock().unwrap_or_else(PoisonError::into_inner)
}
}