use std::time::Instant;
#[derive(Debug, Clone)]
pub struct EvalBudget {
pub max_steps: u64,
pub max_alloc_bytes: u64,
pub deadline: Option<Instant>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum BudgetExceededKind {
Steps,
Alloc,
Deadline,
}
impl EvalBudget {
pub const fn unlimited() -> Self {
Self {
max_steps: u64::MAX,
max_alloc_bytes: u64::MAX,
deadline: None,
}
}
pub const fn min_viable() -> Self {
Self {
max_steps: 1,
max_alloc_bytes: 1024,
deadline: None,
}
}
pub const fn for_batch(steps: u64, alloc: u64) -> Self {
Self {
max_steps: steps,
max_alloc_bytes: alloc,
deadline: None,
}
}
pub fn for_interactive(deadline: Instant) -> Self {
Self {
max_steps: u64::MAX,
max_alloc_bytes: u64::MAX,
deadline: Some(deadline),
}
}
#[inline]
pub fn check(&self, steps: u64, alloc_bytes: u64) -> Result<(), BudgetExceededKind> {
if steps > self.max_steps {
return Err(BudgetExceededKind::Steps);
}
if alloc_bytes > self.max_alloc_bytes {
return Err(BudgetExceededKind::Alloc);
}
if let Some(deadline) = self.deadline {
if Instant::now() >= deadline {
return Err(BudgetExceededKind::Deadline);
}
}
Ok(())
}
}