use std::sync::Arc;
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use crate::{Result, ZuError};
#[derive(Debug, Default)]
struct Shared {
stop: AtomicBool,
rows: AtomicU64,
}
#[derive(Clone, Debug, Default)]
pub struct Interrupt(Option<Arc<Shared>>);
impl Interrupt {
pub fn armed() -> Interrupt {
Interrupt(Some(Arc::new(Shared::default())))
}
pub fn stop(&self) {
if let Some(shared) = &self.0 {
shared.stop.store(true, Ordering::Relaxed);
}
}
pub fn stopped(&self) -> bool {
self.0
.as_ref()
.is_some_and(|shared| shared.stop.load(Ordering::Relaxed))
}
pub fn check(&self) -> Result<()> {
if self.stopped() {
return Err(ZuError::Interrupted);
}
Ok(())
}
pub fn clear(&self) {
if let Some(shared) = &self.0 {
shared.stop.store(false, Ordering::Relaxed);
shared.rows.store(0, Ordering::Relaxed);
}
}
pub fn read(&self, rows: u64) {
if let Some(shared) = &self.0 {
shared.rows.fetch_add(rows, Ordering::Relaxed);
}
}
pub fn rows(&self) -> u64 {
self.0
.as_ref()
.map_or(0, |shared| shared.rows.load(Ordering::Relaxed))
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn an_armed_handle_stops_and_a_default_one_never_does() {
let armed = Interrupt::armed();
assert!(!armed.stopped());
assert!(armed.check().is_ok());
armed.stop();
assert!(armed.stopped());
assert!(matches!(armed.check(), Err(ZuError::Interrupted)));
let never = Interrupt::default();
never.stop();
assert!(!never.stopped());
assert!(never.check().is_ok());
}
#[test]
fn every_clone_is_the_same_word() {
let held = Interrupt::armed();
let handed = held.clone();
handed.read(2048);
held.read(2048);
assert_eq!(held.rows(), 4096);
assert_eq!(handed.rows(), 4096);
held.stop();
assert!(handed.stopped(), "the executor's copy sees the ask");
handed.clear();
assert!(!held.stopped());
assert_eq!(held.rows(), 0);
}
#[test]
fn a_default_handle_counts_nothing_and_answers_nothing() {
let never = Interrupt::default();
never.read(4096);
assert_eq!(never.rows(), 0);
}
}