Skip to main content

crous_core/
limits.rs

1//! Configurable resource limits for decoding, to prevent denial-of-service attacks.
2//!
3//! All limits have sane defaults and can be overridden per-decoder instance.
4
5/// Resource limits for decoder operations.
6#[derive(Debug, Clone)]
7pub struct Limits {
8    /// Maximum nesting depth for objects/arrays (default: 128).
9    pub max_nesting_depth: usize,
10    /// Maximum size of a single block in bytes (default: 64 MiB).
11    pub max_block_size: usize,
12    /// Maximum number of items in a single array or object (default: 1M).
13    pub max_items: usize,
14    /// Maximum total memory allocation for a single decode session (default: 256 MiB).
15    pub max_memory: usize,
16    /// Maximum string length in bytes (default: 16 MiB).
17    pub max_string_length: usize,
18}
19
20impl Default for Limits {
21    fn default() -> Self {
22        Self {
23            max_nesting_depth: 128,
24            max_block_size: 64 * 1024 * 1024,    // 64 MiB
25            max_items: 1_000_000,                // 1M items
26            max_memory: 256 * 1024 * 1024,       // 256 MiB
27            max_string_length: 16 * 1024 * 1024, // 16 MiB
28        }
29    }
30}
31
32impl Limits {
33    /// Restrictive limits suitable for untrusted input.
34    pub fn strict() -> Self {
35        Self {
36            max_nesting_depth: 32,
37            max_block_size: 1024 * 1024, // 1 MiB
38            max_items: 10_000,
39            max_memory: 4 * 1024 * 1024, // 4 MiB
40            max_string_length: 65536,    // 64 KiB
41        }
42    }
43
44    /// No limits — for trusted data only.
45    pub fn unlimited() -> Self {
46        Self {
47            max_nesting_depth: usize::MAX,
48            max_block_size: usize::MAX,
49            max_items: usize::MAX,
50            max_memory: usize::MAX,
51            max_string_length: usize::MAX,
52        }
53    }
54}