use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use tokio_util::sync::CancellationToken;
#[derive(Clone, Debug)]
pub struct CancelHandle {
flag: Arc<AtomicBool>,
token: CancellationToken,
}
impl Default for CancelHandle {
fn default() -> Self {
Self::new()
}
}
impl CancelHandle {
pub fn new() -> Self {
Self {
flag: Arc::new(AtomicBool::new(false)),
token: CancellationToken::new(),
}
}
pub fn flag(&self) -> Arc<AtomicBool> {
Arc::clone(&self.flag)
}
pub fn token(&self) -> CancellationToken {
self.token.clone()
}
pub fn is_cancelled(&self) -> bool {
self.flag.load(Ordering::Relaxed) || self.token.is_cancelled()
}
pub fn trip(&self) {
self.flag.store(true, Ordering::Relaxed);
self.token.cancel();
}
pub async fn cancelled(&self) {
self.token.cancelled().await
}
}