use std::sync::atomic::{AtomicBool, Ordering};
pub trait Cancelation {
fn should_cancel(&self) -> bool;
}
pub struct AtomicCancelation<'a>(&'a AtomicBool);
impl<'a> AtomicCancelation<'a> {
pub fn new(val: &'a AtomicBool) -> Self {
Self(val)
}
}
impl Cancelation for AtomicCancelation<'_> {
fn should_cancel(&self) -> bool {
self.0.load(Ordering::Relaxed)
}
}
pub struct DontCancel;
impl Cancelation for DontCancel {
fn should_cancel(&self) -> bool {
false
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_atomic_cancelation() {
let x = AtomicBool::new(false);
let y = AtomicCancelation::new(&x);
assert!(!y.should_cancel());
x.store(true, Ordering::Relaxed);
assert!(y.should_cancel());
}
#[test]
fn test_no_cancelation() {
let x = DontCancel;
assert!(!x.should_cancel());
}
}