#[cfg(feature = "signals")]
use std::process;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
#[cfg(feature = "signals")]
use std::sync::{Mutex, OnceLock, PoisonError};
use std::thread;
use std::time::{Duration, Instant};
const WAIT_STEP: Duration = Duration::from_millis(250);
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum StopReason {
Requested,
TimeLimit,
}
#[derive(Debug, Clone, Default)]
pub struct Stop {
requested: Arc<AtomicBool>,
deadline: Option<Instant>,
}
impl Stop {
#[must_use]
pub fn new() -> Self {
Self::default()
}
#[must_use]
pub fn with_max_runtime(mut self, runtime: Duration) -> Self {
self.deadline = Instant::now().checked_add(runtime);
self
}
pub fn request(&self) {
self.requested.store(true, Ordering::SeqCst);
}
#[must_use]
pub fn reason(&self) -> Option<StopReason> {
self.reason_at(Instant::now())
}
fn reason_at(&self, now: Instant) -> Option<StopReason> {
if self.requested.load(Ordering::SeqCst) {
Some(StopReason::Requested)
} else if self.deadline.is_some_and(|deadline| now >= deadline) {
Some(StopReason::TimeLimit)
} else {
None
}
}
#[must_use]
pub fn wait(&self, duration: Duration) -> Option<StopReason> {
let end = Instant::now().checked_add(duration);
loop {
if let Some(reason) = self.reason() {
return Some(reason);
}
let left = end.map_or(WAIT_STEP, |end| {
end.saturating_duration_since(Instant::now())
});
if left.is_zero() {
return None;
}
thread::sleep(left.min(WAIT_STEP));
}
}
}
#[cfg(feature = "signals")]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Signal {
First,
Again,
}
#[cfg(feature = "signals")]
#[derive(Debug, thiserror::Error)]
#[error("cannot handle Ctrl+C, SIGTERM and SIGHUP: {0}")]
pub struct SignalError(String);
#[cfg(feature = "signals")]
const AGAIN_EXIT_STATUS: i32 = 130;
#[cfg(feature = "signals")]
struct Listener {
stop: Stop,
notify: Box<dyn Fn(Signal) + Send>,
}
#[cfg(feature = "signals")]
static LISTENER: Mutex<Option<Listener>> = Mutex::new(None);
#[cfg(feature = "signals")]
static INSTALLED: OnceLock<Result<(), String>> = OnceLock::new();
#[cfg(feature = "signals")]
fn dispatch() {
let listener = LISTENER.lock().unwrap_or_else(PoisonError::into_inner);
let Some(listener) = listener.as_ref() else {
exit_now();
};
let signal = listener.stop.advance();
(listener.notify)(signal);
if signal == Signal::Again {
exit_now();
}
}
#[cfg(feature = "signals")]
impl Stop {
pub fn on_signals(
&self,
notify: impl Fn(Signal) + Send + 'static,
) -> Result<SignalGuard, SignalError> {
INSTALLED
.get_or_init(|| ctrlc::set_handler(dispatch).map_err(|e| e.to_string()))
.clone()
.map_err(SignalError)?;
*LISTENER.lock().unwrap_or_else(PoisonError::into_inner) = Some(Listener {
stop: self.clone(),
notify: Box::new(notify),
});
Ok(SignalGuard {
requested: Arc::clone(&self.requested),
})
}
fn advance(&self) -> Signal {
if self.requested.swap(true, Ordering::SeqCst) {
Signal::Again
} else {
Signal::First
}
}
}
#[cfg(feature = "signals")]
#[must_use = "dropping the guard makes the next signal end the process at once"]
#[derive(Debug)]
pub struct SignalGuard {
requested: Arc<AtomicBool>,
}
#[cfg(feature = "signals")]
impl Drop for SignalGuard {
fn drop(&mut self) {
let mut listener = LISTENER.lock().unwrap_or_else(PoisonError::into_inner);
if listener
.as_ref()
.is_some_and(|l| Arc::ptr_eq(&l.stop.requested, &self.requested))
{
*listener = None;
}
}
}
#[cfg(feature = "signals")]
#[expect(
clippy::exit,
reason = "a second signal ends the process at once, which is what it asks for"
)]
fn exit_now() -> ! {
process::exit(AGAIN_EXIT_STATUS)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn nothing_asks_without_a_request_or_a_limit() {
assert_eq!(Stop::new().reason(), None);
}
#[test]
fn a_request_is_seen_by_every_clone() {
let stop = Stop::new();
let clone = stop.clone();
assert_eq!(clone.reason(), None);
stop.request();
assert_eq!(clone.reason(), Some(StopReason::Requested));
}
#[test]
fn the_time_limit_asks_once_it_has_passed() {
let stop = Stop::new().with_max_runtime(Duration::from_mins(1));
let now = Instant::now();
assert_eq!(stop.reason_at(now), None);
assert_eq!(stop.reason_at(now + Duration::from_secs(59)), None);
assert_eq!(
stop.reason_at(now + Duration::from_mins(2)),
Some(StopReason::TimeLimit)
);
assert_eq!(
Stop::new().with_max_runtime(Duration::ZERO).reason(),
Some(StopReason::TimeLimit)
);
}
#[test]
fn a_runtime_too_long_to_count_is_no_limit() {
assert_eq!(Stop::new().with_max_runtime(Duration::MAX).reason(), None);
}
#[test]
fn a_request_is_reported_before_the_time_limit() {
let stop = Stop::new().with_max_runtime(Duration::ZERO);
stop.request();
assert_eq!(stop.reason(), Some(StopReason::Requested));
}
#[test]
fn waiting_ends_early_on_a_request_and_late_without_one() {
let started = Instant::now();
let asked = Stop::new();
asked.request();
assert_eq!(
asked.wait(Duration::from_mins(1)),
Some(StopReason::Requested)
);
assert!(started.elapsed() < Duration::from_secs(10));
assert_eq!(Stop::new().wait(Duration::from_millis(30)), None);
}
#[test]
fn waiting_ends_at_the_time_limit() {
let stop = Stop::new().with_max_runtime(Duration::from_millis(30));
assert_eq!(
stop.wait(Duration::from_mins(1)),
Some(StopReason::TimeLimit)
);
}
#[cfg(feature = "signals")]
#[test]
fn the_first_signal_requests_and_every_later_one_asks_to_stop_at_once() {
let stop = Stop::new();
assert_eq!(stop.advance(), Signal::First);
assert_eq!(stop.reason(), Some(StopReason::Requested));
assert_eq!(stop.advance(), Signal::Again);
assert_eq!(stop.advance(), Signal::Again);
}
#[cfg(feature = "signals")]
#[test]
fn the_handler_tells_the_latest_stop_while_its_guard_lives() {
let listens = |stop: &Stop| {
LISTENER
.lock()
.unwrap()
.as_ref()
.is_some_and(|l| Arc::ptr_eq(&l.stop.requested, &stop.requested))
};
let (first, second) = (Stop::new(), Stop::new());
let first_guard = first.on_signals(|_| {}).unwrap();
assert!(listens(&first));
let second_guard = second.on_signals(|_| {}).unwrap();
assert!(listens(&second));
drop(first_guard);
assert!(listens(&second));
drop(second_guard);
assert!(LISTENER.lock().unwrap().is_none());
}
#[cfg(feature = "signals")]
#[test]
fn a_signal_after_a_request_asks_to_stop_at_once() {
let stop = Stop::new();
stop.request();
assert_eq!(stop.advance(), Signal::Again);
}
}