Skip to main content

laminapdf_syntax/
cancel.rs

1//! The cancel flag shared by long calls and jobs ([ADR 0028] §5). It lives in the lowest core
2//! crate so every crate that does long work (the façade's jobs, `laminapdf-render`'s renders) takes
3//! the same type; the façade re-exports it as `laminapdf::CancelToken`.
4//!
5//! [ADR 0028]: https://github.com/laudebugs/laminapdf/blob/main/docs/decisions/0028-facade-rules-jobs-and-cancellation.md
6
7use std::sync::Arc;
8use std::sync::atomic::{AtomicBool, Ordering};
9
10/// A cancel flag shared by the jobs and calls it is passed to ([ADR 0028] §5). Cloning
11/// shares the flag: cancel one clone and every holder sees it.
12///
13/// An atomic flag, not a lock or a cache, so a document holding one stays `Send + !Sync`
14/// (ADR 0005 §7). The core polls it at the start of every step, at every budget check and
15/// inside long loops; a tripped token makes the call fail with `cancelled`.
16///
17/// [ADR 0028]: https://github.com/laudebugs/laminapdf/blob/main/docs/decisions/0028-facade-rules-jobs-and-cancellation.md
18///
19/// Added in 0.2.0.
20#[derive(Debug, Clone, Default)]
21pub struct CancelToken(Arc<AtomicBool>);
22
23impl CancelToken {
24    /// A token that is not cancelled.
25    ///
26    /// Added in 0.2.0.
27    #[must_use]
28    pub fn new() -> Self {
29        Self::default()
30    }
31
32    /// Cancels every job and call holding this token (or a clone).
33    ///
34    /// Added in 0.2.0.
35    pub fn cancel(&self) {
36        // Relaxed is enough: a flag, no data is published through it.
37        self.0.store(true, Ordering::Relaxed);
38    }
39
40    /// Whether [`CancelToken::cancel`] was called.
41    ///
42    /// Added in 0.2.0.
43    #[must_use]
44    pub fn is_cancelled(&self) -> bool {
45        self.0.load(Ordering::Relaxed)
46    }
47}
48
49#[cfg(test)]
50mod tests {
51    use super::CancelToken;
52
53    #[test]
54    fn a_clone_shares_the_flag() {
55        let token = CancelToken::new();
56        let clone = token.clone();
57        assert!(!clone.is_cancelled());
58        token.cancel();
59        assert!(clone.is_cancelled());
60    }
61}