use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
use crate::{PvError, Result};
#[derive(Clone, Debug, Default)]
pub struct CancellationToken {
cancelled: Arc<AtomicBool>,
}
impl CancellationToken {
pub fn new() -> Self {
Self::default()
}
pub fn cancel(&self) {
self.cancelled.store(true, Ordering::Release);
}
pub fn is_cancelled(&self) -> bool {
self.cancelled.load(Ordering::Acquire)
}
pub(crate) fn check(&self) -> Result<()> {
if self.is_cancelled() {
Err(PvError::Cancelled)
} else {
Ok(())
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn clones_share_cancellation_state() {
let token = CancellationToken::new();
let clone = token.clone();
assert!(!clone.is_cancelled());
token.cancel();
assert!(clone.is_cancelled());
assert!(matches!(clone.check(), Err(PvError::Cancelled)));
}
}