Skip to main content

irtt_client/managed/
cancellation.rs

1use std::sync::{
2    atomic::{AtomicBool, Ordering},
3    Arc,
4};
5
6#[derive(Debug, Clone, Default)]
7pub struct CancellationToken {
8    cancelled: Arc<AtomicBool>,
9}
10
11impl CancellationToken {
12    pub fn new() -> Self {
13        Self::default()
14    }
15
16    pub fn cancel(&self) {
17        self.cancelled.store(true, Ordering::SeqCst);
18    }
19
20    #[must_use]
21    pub fn is_cancelled(&self) -> bool {
22        self.cancelled.load(Ordering::SeqCst)
23    }
24}
25
26#[cfg(test)]
27mod tests {
28    use super::*;
29
30    #[test]
31    fn token_starts_uncancelled() {
32        assert!(!CancellationToken::new().is_cancelled());
33    }
34
35    #[test]
36    fn cancel_is_idempotent_and_visible_through_clones() {
37        let token = CancellationToken::new();
38        let clone = token.clone();
39
40        token.cancel();
41        token.cancel();
42
43        assert!(token.is_cancelled());
44        assert!(clone.is_cancelled());
45    }
46}