crumbkit_process/cancel.rs
1//! The handle that stops a run from another thread.
2
3use std::sync::{Arc, Mutex, MutexGuard, PoisonError, Weak};
4
5use crate::notice::Notice;
6
7/// A handle that stops the runs that watch it.
8///
9/// A run watches a cancel that [`Run::cancel`](crate::Run::cancel) gave it.
10/// [`Cancel::cancel`] stops each watching run with its escalation, and the
11/// run ends as [`Stopped(Cancelled)`](crate::Stop::Cancelled). A run that
12/// starts with a cancel that is already cancelled starts no child. Clones
13/// share one state, so any clone cancels, and a cancel stays cancelled.
14#[derive(Clone, Debug, Default)]
15pub struct Cancel(Arc<Mutex<Watched>>);
16
17/// Whether a cancel was cancelled, and the runs that watch it.
18#[derive(Debug, Default)]
19struct Watched {
20 cancelled: bool,
21 runs: Vec<Weak<Notice>>,
22}
23
24impl Cancel {
25 /// Returns a cancel that is not cancelled.
26 #[must_use]
27 pub fn new() -> Self {
28 Self::default()
29 }
30
31 /// Cancels every run that watches this cancel or that starts watching it
32 /// later.
33 pub fn cancel(&self) {
34 let mut watched = self.lock();
35 watched.cancelled = true;
36 for run in watched.runs.drain(..).filter_map(|run| run.upgrade()) {
37 run.set(|flags| flags.cancelled = true);
38 }
39 }
40
41 /// Returns true once [`Cancel::cancel`] has been called on this cancel or
42 /// a clone of it.
43 #[must_use]
44 pub fn is_cancelled(&self) -> bool {
45 self.lock().cancelled
46 }
47
48 /// Makes the run that `notice` wakes watch this cancel, and sets its
49 /// flag at once when this cancel is already cancelled. It forgets the
50 /// runs that have ended.
51 pub(crate) fn watch(&self, notice: &Arc<Notice>) {
52 let mut watched = self.lock();
53 if watched.cancelled {
54 notice.set(|flags| flags.cancelled = true);
55 return;
56 }
57 watched.runs.retain(|run| run.strong_count() > 0);
58 watched.runs.push(Arc::downgrade(notice));
59 }
60
61 /// Returns the locked state. Each holder only reads or changes it in one
62 /// step, so a panic while the lock was held leaves nothing half changed.
63 fn lock(&self) -> MutexGuard<'_, Watched> {
64 self.0.lock().unwrap_or_else(PoisonError::into_inner)
65 }
66}