Skip to main content

jsonx_lib/
limits.rs

1//! Budgets on what a document may cost to read.
2
3/// Budgets on the work and memory a document may cost.
4///
5/// Every budget is checked before the memory it guards is allocated, so a
6/// hostile document is refused while it is still cheap to refuse. None of them
7/// is there to protect the stack: the parser, the writer, and every operation
8/// on [`Value`](crate::Value) use a bounded amount of stack whatever the
9/// nesting depth (explicit stacks on the heap; drop recurses at most a fixed
10/// 32 levels). The depth budget exists for the code that consumes the value,
11/// which may well be recursive.
12///
13/// | Budget | Default | Counts |
14/// |---|---:|---|
15/// | [`max_depth`](Self::max_depth) | 128 | nested arrays and objects; a scalar at the top is depth 0, `[]` is 1 |
16/// | [`max_input_bytes`](Self::max_input_bytes) | 64 MiB | bytes of input |
17/// | [`max_string_bytes`](Self::max_string_bytes) | 16 MiB | source bytes between a string's quotes, keys included |
18/// | [`max_number_bytes`](Self::max_number_bytes) | 1 KiB | bytes of a number's text |
19/// | [`max_elements`](Self::max_elements) | 4 Mi | values in the document: every scalar, array, and object counts one |
20///
21/// The depth default matches `serde_json`'s recursion limit, so code moving
22/// from it sees the same behaviour. A string's budget is measured in source
23/// bytes, which is never less than its decoded length, so the check can run
24/// before the string is decoded.
25///
26/// The struct is `#[non_exhaustive]`: start from [`Limits::default`] or
27/// [`Limits::unlimited`] and change the fields you care about, or chain the
28/// `with_*` methods.
29///
30/// # Examples
31///
32/// ```
33/// use jsonx_lib::{Limits, Parser, ErrorKind};
34///
35/// let strict = Parser::new().limits(Limits::default().with_max_depth(2));
36/// assert!(strict.parse("[[1]]").is_ok());
37/// let err = strict.parse("[[[1]]]").unwrap_err();
38/// assert_eq!(err.kind(), ErrorKind::DepthLimitExceeded);
39/// assert_eq!(err.offset(), 2);
40///
41/// let mut limits = Limits::default();
42/// limits.max_string_bytes = 4;
43/// assert!(Parser::new().limits(limits).parse(r#""abcde""#).is_err());
44/// ```
45#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
46#[non_exhaustive]
47pub struct Limits {
48    /// The deepest nesting of arrays and objects allowed. `0` allows only a
49    /// scalar document.
50    pub max_depth: usize,
51    /// The longest input accepted, in bytes.
52    pub max_input_bytes: usize,
53    /// The longest string or key accepted, in source bytes between the quotes
54    /// (escape sequences count at their written length).
55    pub max_string_bytes: usize,
56    /// The longest number accepted, in bytes of its text.
57    pub max_number_bytes: usize,
58    /// The most values a document may hold, counting every scalar, array, and
59    /// object (keys are not counted separately).
60    pub max_elements: usize,
61}
62
63impl Limits {
64    /// The default budgets (see the table on [`Limits`]): generous for real
65    /// documents, small enough that a hostile one cannot exhaust memory.
66    ///
67    /// # Examples
68    ///
69    /// ```
70    /// use jsonx_lib::Limits;
71    ///
72    /// assert_eq!(Limits::new().max_depth, 128);
73    /// assert_eq!(Limits::new(), Limits::default());
74    /// ```
75    #[must_use]
76    pub const fn new() -> Self {
77        Self {
78            max_depth: 128,
79            max_input_bytes: 64 * 1024 * 1024,
80            max_string_bytes: 16 * 1024 * 1024,
81            max_number_bytes: 1024,
82            max_elements: 4 * 1024 * 1024,
83        }
84    }
85
86    /// No budgets at all: every limit is `usize::MAX`. For input you trust;
87    /// even then the parser cannot overflow the stack, because nothing in this
88    /// crate recurses on nesting depth.
89    ///
90    /// # Examples
91    ///
92    /// ```
93    /// use jsonx_lib::{Limits, Parser};
94    ///
95    /// let deep = format!("{}{}", "[".repeat(1000), "]".repeat(1000));
96    /// assert!(Parser::new().limits(Limits::unlimited()).parse(&deep).is_ok());
97    /// ```
98    #[must_use]
99    pub const fn unlimited() -> Self {
100        Self {
101            max_depth: usize::MAX,
102            max_input_bytes: usize::MAX,
103            max_string_bytes: usize::MAX,
104            max_number_bytes: usize::MAX,
105            max_elements: usize::MAX,
106        }
107    }
108
109    /// Sets [`max_depth`](Self::max_depth).
110    ///
111    /// # Examples
112    ///
113    /// ```
114    /// use jsonx_lib::Limits;
115    ///
116    /// assert_eq!(Limits::new().with_max_depth(8).max_depth, 8);
117    /// ```
118    #[must_use]
119    pub const fn with_max_depth(mut self, depth: usize) -> Self {
120        self.max_depth = depth;
121        self
122    }
123
124    /// Sets [`max_input_bytes`](Self::max_input_bytes).
125    ///
126    /// # Examples
127    ///
128    /// ```
129    /// use jsonx_lib::{ErrorKind, Limits, Parser};
130    ///
131    /// let p = Parser::new().limits(Limits::new().with_max_input_bytes(4));
132    /// assert!(p.parse("1234").is_ok());
133    /// assert_eq!(p.parse("12345").unwrap_err().kind(), ErrorKind::InputTooLarge);
134    /// ```
135    #[must_use]
136    pub const fn with_max_input_bytes(mut self, bytes: usize) -> Self {
137        self.max_input_bytes = bytes;
138        self
139    }
140
141    /// Sets [`max_string_bytes`](Self::max_string_bytes).
142    ///
143    /// # Examples
144    ///
145    /// ```
146    /// use jsonx_lib::{ErrorKind, Limits, Parser};
147    ///
148    /// let p = Parser::new().limits(Limits::new().with_max_string_bytes(2));
149    /// assert!(p.parse(r#"{"ab": "cd"}"#).is_ok());
150    /// assert_eq!(p.parse(r#"{"abc": 1}"#).unwrap_err().kind(), ErrorKind::StringTooLong);
151    /// ```
152    #[must_use]
153    pub const fn with_max_string_bytes(mut self, bytes: usize) -> Self {
154        self.max_string_bytes = bytes;
155        self
156    }
157
158    /// Sets [`max_number_bytes`](Self::max_number_bytes).
159    ///
160    /// # Examples
161    ///
162    /// ```
163    /// use jsonx_lib::{ErrorKind, Limits, Parser};
164    ///
165    /// let p = Parser::new().limits(Limits::new().with_max_number_bytes(3));
166    /// assert!(p.parse("-12").is_ok());
167    /// assert_eq!(p.parse("1e10").unwrap_err().kind(), ErrorKind::NumberTooLong);
168    /// ```
169    #[must_use]
170    pub const fn with_max_number_bytes(mut self, bytes: usize) -> Self {
171        self.max_number_bytes = bytes;
172        self
173    }
174
175    /// Sets [`max_elements`](Self::max_elements).
176    ///
177    /// # Examples
178    ///
179    /// ```
180    /// use jsonx_lib::{ErrorKind, Limits, Parser};
181    ///
182    /// // The array itself is one value, so `[1, 2]` holds three.
183    /// let p = Parser::new().limits(Limits::new().with_max_elements(3));
184    /// assert!(p.parse("[1, 2]").is_ok());
185    /// assert_eq!(p.parse("[1, 2, 3]").unwrap_err().kind(), ErrorKind::TooManyElements);
186    /// ```
187    #[must_use]
188    pub const fn with_max_elements(mut self, count: usize) -> Self {
189        self.max_elements = count;
190        self
191    }
192}
193
194impl Default for Limits {
195    #[inline]
196    fn default() -> Self {
197        Self::new()
198    }
199}
200
201#[cfg(test)]
202mod tests {
203    use super::*;
204
205    #[test]
206    fn test_limits_default_matches_documented_table() {
207        let l = Limits::default();
208        assert_eq!(l.max_depth, 128);
209        assert_eq!(l.max_input_bytes, 64 << 20);
210        assert_eq!(l.max_string_bytes, 16 << 20);
211        assert_eq!(l.max_number_bytes, 1024);
212        assert_eq!(l.max_elements, 4 << 20);
213    }
214
215    #[test]
216    fn test_limits_setters_chain() {
217        let l = Limits::unlimited()
218            .with_max_depth(1)
219            .with_max_input_bytes(2)
220            .with_max_string_bytes(3)
221            .with_max_number_bytes(4)
222            .with_max_elements(5);
223        assert_eq!(
224            (
225                l.max_depth,
226                l.max_input_bytes,
227                l.max_string_bytes,
228                l.max_number_bytes,
229                l.max_elements
230            ),
231            (1, 2, 3, 4, 5)
232        );
233    }
234}