use core::sync::atomic::{AtomicBool, Ordering};
pub trait Cancel {
fn is_cancelled(&self) -> bool;
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)]
pub struct NoCancel;
impl Cancel for NoCancel {
fn is_cancelled(&self) -> bool {
false
}
}
impl Cancel for AtomicBool {
fn is_cancelled(&self) -> bool {
self.load(Ordering::Relaxed)
}
}
impl<T: Cancel + ?Sized> Cancel for &T {
fn is_cancelled(&self) -> bool {
(**self).is_cancelled()
}
}
#[cfg(test)]
mod tests {
use super::*;
fn stopped(cancel: impl Cancel) -> bool {
cancel.is_cancelled()
}
#[test]
fn a_flag_cancels_once_set_and_no_cancel_never_does() {
let flag = AtomicBool::new(false);
assert!(!stopped(&flag));
flag.store(true, Ordering::Relaxed);
assert!(stopped(&flag));
let dynamic: &dyn Cancel = &flag;
assert!(stopped(dynamic));
assert!(!stopped(NoCancel));
}
}