use crate::error::{PyrucastError, Result};
pub trait Cancel {
fn check(&self) -> Result<()>;
}
impl<C: Cancel + ?Sized> Cancel for &C {
fn check(&self) -> Result<()> {
(**self).check()
}
}
pub struct NoCancel;
impl Cancel for NoCancel {
#[inline]
fn check(&self) -> Result<()> {
Ok(())
}
}
impl Cancel for () {
#[inline]
fn check(&self) -> Result<()> {
Ok(())
}
}
impl Cancel for std::sync::atomic::AtomicBool {
#[inline]
fn check(&self) -> Result<()> {
if self.load(std::sync::atomic::Ordering::Relaxed) {
Err(PyrucastError::Interrupted)
} else {
Ok(())
}
}
}
pub struct Deadline(pub std::time::Instant);
impl Deadline {
pub fn after(dur: std::time::Duration) -> Self {
Deadline(std::time::Instant::now() + dur)
}
}
impl Cancel for Deadline {
#[inline]
fn check(&self) -> Result<()> {
if std::time::Instant::now() >= self.0 {
Err(PyrucastError::Interrupted)
} else {
Ok(())
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::sync::atomic::{AtomicBool, Ordering};
#[test]
fn no_cancel_never_trips() {
assert!(NoCancel.check().is_ok());
assert!(().check().is_ok());
}
#[test]
fn atomic_flag_trips_when_set() {
let flag = AtomicBool::new(false);
assert!(flag.check().is_ok());
flag.store(true, Ordering::Relaxed);
assert!(matches!(flag.check(), Err(PyrucastError::Interrupted)));
let r = &flag;
assert!(matches!(r.check(), Err(PyrucastError::Interrupted)));
}
#[test]
fn deadline_trips_in_the_past() {
let past = Deadline(std::time::Instant::now() - std::time::Duration::from_secs(1));
assert!(matches!(past.check(), Err(PyrucastError::Interrupted)));
let future = Deadline::after(std::time::Duration::from_secs(3600));
assert!(future.check().is_ok());
}
}