v0.3.6-pre.002
This commit is contained in:
44
crates/ksp-job-api/src/cancellation.rs
Normal file
44
crates/ksp-job-api/src/cancellation.rs
Normal file
@@ -0,0 +1,44 @@
|
||||
// file: crates/ksp-job-api/src/cancellation.rs
|
||||
// version: 1
|
||||
|
||||
/// Runtime-neutral cloneable token carrying cooperative cancellation intent.
|
||||
#[derive(Clone)]
|
||||
pub struct JobCancellationToken {
|
||||
requested: std::sync::Arc<std::sync::atomic::AtomicBool>,
|
||||
}
|
||||
|
||||
impl JobCancellationToken {
|
||||
/// Creates a token with no cancellation request.
|
||||
#[must_use]
|
||||
pub fn new() -> Self {
|
||||
return Self { requested: std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)) };
|
||||
}
|
||||
|
||||
/// Requests cancellation and returns `true` only for the first request shared by all clones.
|
||||
#[must_use]
|
||||
pub fn cancel(&self) -> bool {
|
||||
return !self.requested.swap(true, std::sync::atomic::Ordering::AcqRel);
|
||||
}
|
||||
|
||||
/// Reports whether cancellation has been requested through any clone.
|
||||
#[must_use]
|
||||
pub fn is_cancellation_requested(&self) -> bool {
|
||||
return self.requested.load(std::sync::atomic::Ordering::Acquire);
|
||||
}
|
||||
}
|
||||
|
||||
impl std::default::Default for JobCancellationToken {
|
||||
fn default() -> Self {
|
||||
return Self::new();
|
||||
}
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for JobCancellationToken {
|
||||
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
return formatter.debug_struct("JobCancellationToken").field("cancellation_requested", &self.is_cancellation_requested()).finish();
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "../unit_tests/cancellation.rs"]
|
||||
mod tests;
|
||||
Reference in New Issue
Block a user