use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
#[derive(Debug, Clone, Default)]
pub struct Halt {
quit: Arc<AtomicBool>,
stop: Arc<AtomicBool>,
}
impl Halt {
pub fn new() -> Halt {
Halt::default()
}
pub fn with_shared_quit(&self) -> Halt {
Halt {
quit: Arc::clone(&self.quit),
stop: Arc::new(AtomicBool::new(false)),
}
}
pub fn quit_flag(&self) -> Arc<AtomicBool> {
Arc::clone(&self.quit)
}
pub fn stop(&self) {
self.stop.store(true, Ordering::Relaxed);
}
pub fn clear_stop(&self) {
self.stop.store(false, Ordering::Relaxed);
}
pub fn is_set(&self) -> bool {
self.quit.load(Ordering::Relaxed) || self.stop.load(Ordering::Relaxed)
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::sync::atomic::Ordering;
#[test]
fn a_stop_ends_the_current_action_until_it_is_cleared() {
let halt = Halt::new();
halt.stop();
let stopped = halt.is_set();
halt.clear_stop();
assert!(stopped);
assert!(!halt.is_set());
}
#[test]
fn a_quit_stays_set_when_the_stop_is_cleared() {
let halt = Halt::new();
halt.quit_flag().store(true, Ordering::Relaxed);
halt.clear_stop();
assert!(halt.is_set());
}
#[test]
fn clones_share_both_flags() {
let halt = Halt::new();
let other = halt.clone();
other.stop();
assert!(halt.is_set());
assert!(!Halt::new().is_set());
}
#[test]
fn shared_quit_isolates_stop_while_forwarding_quit() {
let main = Halt::new();
let side = main.with_shared_quit();
main.stop();
assert!(main.is_set());
assert!(!side.is_set());
main.clear_stop();
main.quit_flag().store(true, Ordering::Relaxed);
assert!(main.is_set());
assert!(side.is_set());
}
}