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