use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
use tokio::sync::Notify;
#[derive(Debug, Clone, Default)]
pub struct CancellationSignal {
inner: Arc<Inner>,
}
#[derive(Debug, Default)]
struct Inner {
cancelled: AtomicBool,
notify: Notify,
}
impl CancellationSignal {
#[must_use]
pub fn new() -> Self {
Self::default()
}
pub fn cancel(&self) {
self.inner.cancelled.store(true, Ordering::SeqCst);
self.inner.notify.notify_waiters();
}
#[must_use]
pub fn is_cancelled(&self) -> bool {
self.inner.cancelled.load(Ordering::SeqCst)
}
pub async fn cancelled(&self) {
loop {
let notified = self.inner.notify.notified();
futures::pin_mut!(notified);
notified.as_mut().enable();
if self.is_cancelled() {
return;
}
notified.await;
}
}
}