1use crate::error::{DiagCode, Diagnostic};
4use crate::span::Span;
5
6#[derive(Debug, Clone)]
7pub struct Budget {
8 pub steps_left: u64,
9 pub workspace_left: u64,
10}
11
12pub const SENTINEL_BYTES: u64 = 42 * 1024 * 1024;
14
15impl Default for Budget {
16 fn default() -> Self {
17 Self {
18 steps_left: 100_000,
19 workspace_left: SENTINEL_BYTES,
20 }
21 }
22}
23
24impl Budget {
25 pub fn from_steps(steps: u64) -> Self {
27 Self {
28 steps_left: steps,
29 workspace_left: SENTINEL_BYTES,
30 }
31 }
32
33 pub fn charge(&mut self, bytes: u64, span: Span) -> Result<(), Diagnostic> {
35 if bytes > self.workspace_left {
36 return Err(Diagnostic::new(
37 DiagCode::E400,
38 span,
39 format!(
40 "workspace budget exhausted ({bytes} bytes requested, {} left; Sentinel is {SENTINEL_BYTES})",
41 self.workspace_left
42 ),
43 ));
44 }
45 self.workspace_left -= bytes;
46 Ok(())
47 }
48
49 pub fn tick(&mut self, span: Span) -> Result<(), Diagnostic> {
51 if self.steps_left == 0 {
52 return Err(Diagnostic::new(
53 DiagCode::E400,
54 span,
55 "instruction budget exhausted",
56 ));
57 }
58 self.steps_left -= 1;
59 Ok(())
60 }
61}