btpc_core/create/
progress.rs

1use crate::{Error, Result};
2
3/// Cooperative cancellation handle shared with long-running core operations.
4#[derive(Clone, Debug, Default)]
5pub struct CancellationToken {
6    cancelled: std::sync::Arc<std::sync::atomic::AtomicBool>,
7}
8
9impl CancellationToken {
10    /// Creates an active token.
11    #[must_use]
12    pub fn new() -> Self {
13        Self::default()
14    }
15
16    /// Requests cancellation.
17    pub fn cancel(&self) {
18        self.cancelled
19            .store(true, std::sync::atomic::Ordering::Release);
20    }
21
22    /// Returns whether cancellation has been requested.
23    #[must_use]
24    pub fn is_cancelled(&self) -> bool {
25        self.cancelled.load(std::sync::atomic::Ordering::Acquire)
26    }
27
28    pub(crate) fn check(&self) -> Result<()> {
29        if self.is_cancelled() {
30            Err(Error::cancelled())
31        } else {
32            Ok(())
33        }
34    }
35}
36
37/// Monotonic progress snapshot for sequential hashing.
38#[derive(Clone, Copy, Debug, Eq, PartialEq)]
39pub struct HashProgress {
40    pub(super) bytes_hashed: u64,
41    pub(super) total_bytes: u64,
42    pub(super) pieces_hashed: u64,
43}
44
45impl HashProgress {
46    /// Creates a progress snapshot for shared core operations.
47    #[must_use]
48    pub const fn new(bytes_hashed: u64, total_bytes: u64, pieces_hashed: u64) -> Self {
49        Self {
50            bytes_hashed,
51            total_bytes,
52            pieces_hashed,
53        }
54    }
55
56    /// Returns bytes consumed from payload files.
57    #[must_use]
58    pub const fn bytes_hashed(self) -> u64 {
59        self.bytes_hashed
60    }
61
62    /// Returns the total expected payload bytes.
63    #[must_use]
64    pub const fn total_bytes(self) -> u64 {
65        self.total_bytes
66    }
67
68    /// Returns completed piece hashes.
69    #[must_use]
70    pub const fn pieces_hashed(self) -> u64 {
71        self.pieces_hashed
72    }
73}
74
75/// Presentation-free observer for hashing progress.
76pub trait ProgressSink: Sync {
77    /// Receives a monotonic progress snapshot.
78    fn on_progress(&self, progress: HashProgress);
79}
80
81/// Zero-overhead progress sink for callers that do not need updates.
82#[derive(Clone, Copy, Debug, Default)]
83pub struct NoProgress;
84
85impl ProgressSink for NoProgress {
86    fn on_progress(&self, _progress: HashProgress) {}
87}