use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::time::{Duration, Instant};
use crate::report::StopReason;
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum StopCause {
Aborted,
TimedOut,
}
#[derive(Debug, Clone)]
pub struct ScanHandle {
stop: Arc<Stop>,
}
#[derive(Debug)]
struct Stop {
aborted: AtomicBool,
deadline: Option<Instant>,
}
impl Default for ScanHandle {
fn default() -> Self {
Self::new()
}
}
impl ScanHandle {
pub fn new() -> Self {
Self::bounded(None)
}
pub fn bounded(budget: Option<Duration>) -> Self {
let deadline = budget.map(|budget| Instant::now() + budget);
Self {
stop: Arc::new(Stop {
aborted: AtomicBool::new(false),
deadline,
}),
}
}
pub fn abort(&self) {
self.stop.aborted.store(true, Ordering::SeqCst);
}
pub fn should_stop(&self) -> bool {
self.stopped().is_some()
}
pub fn stopped(&self) -> Option<StopCause> {
if self
.stop
.deadline
.is_some_and(|deadline| Instant::now() >= deadline)
{
return Some(StopCause::TimedOut);
}
if self.stop.aborted.load(Ordering::SeqCst) {
return Some(StopCause::Aborted);
}
None
}
pub fn deadline(&self) -> Option<Instant> {
self.stop.deadline
}
}
impl From<StopCause> for StopReason {
fn from(cause: StopCause) -> Self {
match cause {
StopCause::Aborted => StopReason::Aborted,
StopCause::TimedOut => StopReason::TimedOut,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_handle_with_no_budget_stops_only_when_asked() {
let handle = ScanHandle::new();
assert_eq!(handle.stopped(), None);
handle.abort();
assert_eq!(handle.stopped(), Some(StopCause::Aborted));
}
#[test]
fn an_expired_budget_stops_a_scan_nobody_touched() {
let handle = ScanHandle::bounded(Some(Duration::ZERO));
assert_eq!(handle.stopped(), Some(StopCause::TimedOut));
assert!(handle.should_stop());
}
#[test]
fn a_budget_still_running_stops_nothing() {
let handle = ScanHandle::bounded(Some(Duration::from_secs(3600)));
let clone = handle.clone();
assert_eq!(handle.stopped(), None);
assert_eq!(clone.deadline(), handle.deadline());
}
#[test]
fn a_late_abort_does_not_rename_an_expired_budget() {
let handle = ScanHandle::bounded(Some(Duration::ZERO));
handle.abort();
assert_eq!(handle.stopped(), Some(StopCause::TimedOut));
}
}