Skip to main content

postproject_core/
cancel.rs

1//! Cooperative cancellation shared between a caller and a long operation.
2
3use std::sync::{
4    Arc,
5    atomic::{AtomicBool, Ordering},
6};
7
8use crate::{Error, ErrorKind, Result};
9
10/// A cloneable flag that asks a running operation to stop.
11///
12/// Clones share one flag. Any thread may cancel; an operation polls
13/// [`Self::check`] at safe points and returns [`ErrorKind::Cancelled`].
14/// Cancellation cannot be undone.
15#[derive(Clone, Debug, Default)]
16pub struct CancellationToken {
17    cancelled: Arc<AtomicBool>,
18}
19
20impl CancellationToken {
21    /// Creates a token that is not cancelled.
22    #[must_use]
23    pub fn new() -> Self {
24        Self::default()
25    }
26
27    /// Requests cancellation of every operation observing this token.
28    pub fn cancel(&self) {
29        self.cancelled.store(true, Ordering::Release);
30    }
31
32    /// Returns whether cancellation was requested.
33    #[must_use]
34    pub fn is_cancelled(&self) -> bool {
35        self.cancelled.load(Ordering::Acquire)
36    }
37
38    /// Returns [`ErrorKind::Cancelled`] once cancellation was requested.
39    ///
40    /// # Errors
41    ///
42    /// Returns [`ErrorKind::Cancelled`] after [`Self::cancel`].
43    pub fn check(&self) -> Result<()> {
44        if self.is_cancelled() {
45            return Err(Error::new(ErrorKind::Cancelled, "operation was cancelled"));
46        }
47        Ok(())
48    }
49}
50
51#[cfg(test)]
52mod tests {
53    use super::*;
54
55    #[test]
56    fn clones_share_cancellation() {
57        let token = CancellationToken::new();
58        let observer = token.clone();
59        assert!(observer.check().is_ok());
60        token.cancel();
61        assert_eq!(
62            observer.check().expect_err("cancelled").kind(),
63            ErrorKind::Cancelled
64        );
65    }
66}