Skip to main content

codec_cbor/general/
limits.rs

1// SPDX-FileCopyrightText: 2026 ReallyMe Technologies Limited
2//
3// SPDX-License-Identifier: MIT OR Apache-2.0
4
5use super::error::{error, CborError, ErrorReason};
6
7/// Hard cap for one received input or protected output: one MiB.
8pub const MAX_BYTES: usize = 1_048_576;
9/// Hard cap for simultaneously open containers and tags.
10pub const MAX_DEPTH: usize = 64;
11/// Hard cap for structural nodes, including tags and string chunks.
12pub const MAX_NODES: usize = 65_536;
13/// Hard cap for entries in one array/map or chunks in one string.
14pub const MAX_ENTRIES: usize = 4_096;
15/// Hard cap for validation work credits.
16pub const MAX_WORK: usize = 67_108_864;
17const DEFAULT_WORK: usize = 16_777_216;
18
19/// Caller-lowerable limits; private fields prevent bypassing hard ceilings.
20#[derive(Clone, Copy, Debug, Eq, PartialEq)]
21pub struct Limits {
22    pub(super) input: usize,
23    pub(super) output: usize,
24    pub(super) depth: usize,
25    pub(super) nodes: usize,
26    pub(super) entries: usize,
27    pub(super) bytes: usize,
28    pub(super) text: usize,
29    pub(super) work: usize,
30}
31
32macro_rules! limit {
33    ($setter:ident, $getter:ident, $field:ident, $ceiling:ident, $doc:literal) => {
34        #[doc = $doc]
35        pub fn $setter(mut self, value: usize) -> Result<Self, CborError> {
36            if value > $ceiling {
37                return Err(error(ErrorReason::InvalidLimit));
38            }
39            self.$field = value;
40            Ok(self)
41        }
42
43        #[doc = $doc]
44        #[must_use]
45        pub const fn $getter(self) -> usize {
46            self.$field
47        }
48    };
49}
50
51impl Limits {
52    limit!(
53        with_input_bytes,
54        input_bytes,
55        input,
56        MAX_BYTES,
57        "Set or inspect the maximum received input bytes."
58    );
59    limit!(
60        with_output_bytes,
61        output_bytes,
62        output,
63        MAX_BYTES,
64        "Set or inspect the maximum encoded output bytes."
65    );
66    limit!(
67        with_depth,
68        depth,
69        depth,
70        MAX_DEPTH,
71        "Set or inspect the maximum simultaneously open containers and tags."
72    );
73    limit!(
74        with_nodes,
75        nodes,
76        nodes,
77        MAX_NODES,
78        "Set or inspect the maximum structural node count."
79    );
80    limit!(
81        with_entries,
82        entries,
83        entries,
84        MAX_ENTRIES,
85        "Set or inspect the maximum entries or chunks in one container."
86    );
87    limit!(
88        with_byte_string_bytes,
89        byte_string_bytes,
90        bytes,
91        MAX_BYTES,
92        "Set or inspect aggregate byte-string content bytes."
93    );
94    limit!(
95        with_text_bytes,
96        text_bytes,
97        text,
98        MAX_BYTES,
99        "Set or inspect aggregate UTF-8 text bytes."
100    );
101    limit!(
102        with_work,
103        work,
104        work,
105        MAX_WORK,
106        "Set or inspect validation work credits, including duplicate-key comparisons."
107    );
108}
109
110impl Default for Limits {
111    fn default() -> Self {
112        Self {
113            input: MAX_BYTES,
114            output: MAX_BYTES,
115            depth: MAX_DEPTH,
116            nodes: MAX_NODES,
117            entries: MAX_ENTRIES,
118            bytes: MAX_BYTES,
119            text: MAX_BYTES,
120            work: DEFAULT_WORK,
121        }
122    }
123}
124
125pub(super) struct Budget {
126    pub(super) limits: Limits,
127    pub(super) work: usize,
128    nodes: usize,
129    bytes: usize,
130    text: usize,
131}
132
133impl Budget {
134    pub(super) const fn new(limits: Limits) -> Self {
135        Self {
136            limits,
137            work: 0,
138            nodes: 0,
139            bytes: 0,
140            text: 0,
141        }
142    }
143
144    pub(super) fn charge(&mut self, amount: usize) -> Result<(), CborError> {
145        self.work = self
146            .work
147            .checked_add(amount)
148            .ok_or(error(ErrorReason::ArithmeticOverflow))?;
149        if self.work > self.limits.work {
150            return Err(error(ErrorReason::WorkLimit));
151        }
152        Ok(())
153    }
154
155    pub(super) fn node(&mut self) -> Result<(), CborError> {
156        self.nodes = self
157            .nodes
158            .checked_add(1)
159            .ok_or(error(ErrorReason::ArithmeticOverflow))?;
160        if self.nodes > self.limits.nodes {
161            return Err(error(ErrorReason::NodeLimit));
162        }
163        Ok(())
164    }
165
166    pub(super) fn declared_nodes(&self, count: usize) -> Result<(), CborError> {
167        let total = self
168            .nodes
169            .checked_add(count)
170            .ok_or(error(ErrorReason::ArithmeticOverflow))?;
171        if total > self.limits.nodes {
172            return Err(error(ErrorReason::NodeLimit));
173        }
174        let work = self
175            .work
176            .checked_add(count)
177            .ok_or(error(ErrorReason::ArithmeticOverflow))?;
178        if work > self.limits.work {
179            return Err(error(ErrorReason::WorkLimit));
180        }
181        Ok(())
182    }
183
184    pub(super) fn contents(&mut self, amount: usize, text: bool) -> Result<(), CborError> {
185        let (count, limit, reason) = if text {
186            (&mut self.text, self.limits.text, ErrorReason::TextLimit)
187        } else {
188            (
189                &mut self.bytes,
190                self.limits.bytes,
191                ErrorReason::ByteStringLimit,
192            )
193        };
194        *count = count
195            .checked_add(amount)
196            .ok_or(error(ErrorReason::ArithmeticOverflow))?;
197        if *count > limit {
198            return Err(error(reason));
199        }
200        Ok(())
201    }
202
203    pub(super) fn enter(&self, depth: usize) -> Result<usize, CborError> {
204        let next = depth
205            .checked_add(1)
206            .ok_or(error(ErrorReason::ArithmeticOverflow))?;
207        if next > self.limits.depth {
208            return Err(error(ErrorReason::DepthLimit));
209        }
210        Ok(next)
211    }
212}