Skip to main content

virtual_file_transfer/
cancellation.rs

1use std::sync::{
2    Arc,
3    atomic::{AtomicBool, Ordering},
4};
5
6/// A shareable token for requesting cooperative transfer cancellation.
7///
8/// Clones refer to the same cancellation state. Calling [`Self::cancel`] on
9/// any clone makes [`Self::is_cancelled`] return `true` on every clone.
10/// Cancellation cannot be reset. An in-progress blocking read is not
11/// interrupted immediately; cancellation is checked at defined points in
12/// the transfer implementation.
13#[derive(Clone, Default)]
14pub struct CancellationToken {
15    cancelled: Arc<AtomicBool>,
16}
17
18impl CancellationToken {
19    /// Creates a token in the non-cancelled state.
20    pub fn new() -> Self {
21        Self::default()
22    }
23
24    /// Requests cancellation for every operation sharing this token.
25    ///
26    /// This method returns immediately and does not wait for a read or transfer
27    /// to stop.
28    pub fn cancel(&self) {
29        self.cancelled.store(true, Ordering::Relaxed);
30    }
31
32    /// Returns whether cancellation has been requested.
33    pub fn is_cancelled(&self) -> bool {
34        self.cancelled.load(Ordering::Relaxed)
35    }
36}