postproject_core/
cancel.rs1use std::sync::{
4 Arc,
5 atomic::{AtomicBool, Ordering},
6};
7
8use crate::{Error, ErrorKind, Result};
9
10#[derive(Clone, Debug, Default)]
16pub struct CancellationToken {
17 cancelled: Arc<AtomicBool>,
18}
19
20impl CancellationToken {
21 #[must_use]
23 pub fn new() -> Self {
24 Self::default()
25 }
26
27 pub fn cancel(&self) {
29 self.cancelled.store(true, Ordering::Release);
30 }
31
32 #[must_use]
34 pub fn is_cancelled(&self) -> bool {
35 self.cancelled.load(Ordering::Acquire)
36 }
37
38 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}