1use crate::v2::error::FormatError;
5
6#[derive(Clone)]
8pub struct Limits {
9 pub max_depth: usize,
12
13 pub max_nodes: usize,
16
17 pub max_loads: usize,
19}
20
21pub(crate) struct Budget {
24 pub nodes: usize,
25 pub loads: usize,
26}
27
28pub(crate) struct Meter<'b> {
29 depth_budget: usize,
30 budget: &'b mut Budget,
31}
32
33impl Limits {
34 pub(crate) fn budget(&self) -> Budget {
35 Budget {
36 nodes: self.max_nodes,
37 loads: self.max_loads,
38 }
39 }
40}
41
42impl<'b> Meter<'b> {
43 pub fn new(max_depth: usize, budget: &'b mut Budget) -> Self {
44 Meter {
45 depth_budget: max_depth,
46 budget,
47 }
48 }
49
50 pub fn nest(&mut self) -> Result<Meter<'_>, FormatError> {
52 if self.depth_budget == 0 {
53 return Err(FormatError::TooDeep);
54 }
55
56 Ok(Meter {
57 depth_budget: self.depth_budget - 1,
58 budget: self.budget,
59 })
60 }
61
62 pub fn alloc(&mut self) -> Result<(), FormatError> {
64 if self.budget.nodes == 0 {
65 return Err(FormatError::TooBig);
66 }
67
68 self.budget.nodes -= 1;
69 Ok(())
70 }
71
72 pub fn load(&mut self) -> Result<(), FormatError> {
74 if self.budget.loads == 0 {
75 return Err(FormatError::TooManyLoads);
76 }
77
78 self.budget.loads -= 1;
79 Ok(())
80 }
81}
82
83impl Default for Limits {
84 fn default() -> Self {
85 Self {
86 max_depth: 32,
87 max_nodes: 32768,
88 max_loads: 8,
89 }
90 }
91}