Skip to main content

ruff_db/
cancellation.rs

1use std::fmt::Formatter;
2use std::sync::Arc;
3use std::sync::atomic::AtomicBool;
4
5/// Signals a [`CancellationToken`] that it should be canceled.
6#[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    /// Creates a new token that uses this source.
25    pub fn token(&self) -> CancellationToken {
26        CancellationToken {
27            cancelled: self.cancelled.clone(),
28        }
29    }
30
31    /// Requests cancellation for operations using this token.
32    pub fn cancel(&self) {
33        self.cancelled
34            .store(true, std::sync::atomic::Ordering::Relaxed);
35    }
36}
37
38/// Token signals whether an operation should be canceled.
39#[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/// The operation was canceled by the provided [`CancellationToken`].
51#[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}