1use std::fmt::Formatter;
2use std::sync::Arc;
3use std::sync::atomic::AtomicBool;
4
5#[derive(Debug, Clone)]
7pub struct CancellationTokenSource {
8 cancelled: Arc<AtomicBool>,
9}
10
11impl Default for CancellationTokenSource {
12 fn default() -> Self {
13 Self::new()
14 }
15}
16
17impl CancellationTokenSource {
18 pub fn new() -> Self {
19 Self {
20 cancelled: Arc::new(AtomicBool::new(false)),
21 }
22 }
23
24 pub fn token(&self) -> CancellationToken {
26 CancellationToken {
27 cancelled: self.cancelled.clone(),
28 }
29 }
30
31 pub fn cancel(&self) {
33 self.cancelled
34 .store(true, std::sync::atomic::Ordering::Relaxed);
35 }
36}
37
38#[derive(Debug, Clone)]
40pub struct CancellationToken {
41 cancelled: Arc<AtomicBool>,
42}
43
44impl CancellationToken {
45 pub fn is_cancelled(&self) -> bool {
46 self.cancelled.load(std::sync::atomic::Ordering::Relaxed)
47 }
48}
49
50#[derive(Debug)]
52pub struct Canceled;
53
54impl std::error::Error for Canceled {}
55
56impl std::fmt::Display for Canceled {
57 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
58 f.write_str("operation was canceled")
59 }
60}