temporal_control/budget.rs
1//! Compute and memory budgets.
2
3use crate::Error;
4
5/// Explicit compute and memory limits for one algorithm invocation.
6///
7/// Every algorithm in this crate takes a budget. When a limit would be exceeded the algorithm
8/// stops and returns [`Error::BudgetExhausted`] or [`Error::MemoryBudgetExceeded`]; it never
9/// returns a partial verdict.
10#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
11pub struct Budget {
12 /// Maximum number of elementary steps (one edge relaxation or one matrix-cell update).
13 pub max_steps: u64,
14 /// Maximum number of distance-matrix cells an algorithm may allocate.
15 ///
16 /// Floyd-Warshall needs `n * n` cells for `n` time points.
17 pub max_cells: usize,
18}
19
20impl Budget {
21 /// A budget with no practical limit, for ground-side use and tests.
22 pub const UNLIMITED: Self = Self {
23 max_steps: u64::MAX,
24 max_cells: usize::MAX,
25 };
26
27 /// Starts metering steps against this budget.
28 #[cfg_attr(
29 not(feature = "alloc"),
30 expect(dead_code, reason = "used by alloc algorithms")
31 )]
32 pub(crate) const fn meter(&self) -> Meter {
33 Meter {
34 remaining: self.max_steps,
35 }
36 }
37
38 /// Checks that `cells` matrix cells fit the memory budget.
39 ///
40 /// # Errors
41 ///
42 /// [`Error::MemoryBudgetExceeded`] when `cells` exceeds [`Budget::max_cells`].
43 #[cfg_attr(
44 not(feature = "alloc"),
45 expect(dead_code, reason = "used by alloc algorithms")
46 )]
47 pub(crate) const fn check_cells(&self, cells: usize) -> Result<(), Error> {
48 if cells > self.max_cells {
49 return Err(Error::MemoryBudgetExceeded);
50 }
51
52 Ok(())
53 }
54}
55
56/// Running step counter derived from a [`Budget`].
57#[derive(Debug)]
58#[cfg_attr(
59 not(feature = "alloc"),
60 expect(dead_code, reason = "used by alloc algorithms")
61)]
62pub(crate) struct Meter {
63 /// Steps still available.
64 remaining: u64,
65}
66
67impl Meter {
68 /// Consumes `steps` steps.
69 ///
70 /// # Errors
71 ///
72 /// [`Error::BudgetExhausted`] when fewer than `steps` steps remain.
73 #[cfg_attr(
74 not(feature = "alloc"),
75 expect(dead_code, reason = "used by alloc algorithms")
76 )]
77 pub(crate) fn spend(&mut self, steps: u64) -> Result<(), Error> {
78 self.remaining = self
79 .remaining
80 .checked_sub(steps)
81 .ok_or(Error::BudgetExhausted)?;
82
83 Ok(())
84 }
85}