use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
use std::time::{Duration, Instant};
#[derive(Clone, Debug)]
pub struct Budget {
deadline: Instant,
cancel: Arc<AtomicBool>,
}
impl Budget {
pub fn new(total: Duration, cancel: Arc<AtomicBool>) -> Self {
Budget {
deadline: Instant::now() + total,
cancel,
}
}
pub fn slice(&self, frac: f64) -> Budget {
let remaining = self.deadline.saturating_duration_since(Instant::now());
let frac = if frac.is_finite() {
frac.clamp(0.0, 1.0)
} else {
0.0
};
Budget {
deadline: Instant::now() + remaining.mul_f64(frac),
cancel: self.cancel.clone(),
}
}
pub fn expired(&self) -> bool {
self.cancelled() || Instant::now() >= self.deadline
}
pub fn cancelled(&self) -> bool {
self.cancel.load(Ordering::SeqCst)
}
pub(crate) fn cancel_flag(&self) -> Arc<AtomicBool> {
self.cancel.clone()
}
pub(crate) fn remaining(&self) -> Duration {
self.deadline.saturating_duration_since(Instant::now())
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_cancelled_budget_reads_expired() {
let c = Arc::new(AtomicBool::new(false));
let b = Budget::new(Duration::from_secs(60), c.clone());
assert!(!b.expired());
c.store(true, Ordering::SeqCst);
assert!(b.expired() && b.cancelled());
}
#[test]
fn a_slice_never_outlives_its_parent() {
let b = Budget::new(Duration::from_millis(10), Arc::new(AtomicBool::new(false)));
std::thread::sleep(Duration::from_millis(15));
assert!(b.slice(0.5).expired());
}
}