Skip to main content

ParserConfig

Struct ParserConfig 

Source
pub struct ParserConfig {
    pub max_depth: Option<usize>,
    pub max_string_length: Option<usize>,
    pub max_array_size: Option<usize>,
    pub max_object_size: Option<usize>,
}
Expand description

Configuration for JSON parser to control resource usage

Default values are chosen for embedded systems with limited resources:

  • Max depth: 32 levels (prevents stack overflow)
  • Max string length: 4096 bytes (prevents excessive memory allocation)
  • Max array size: 1024 elements
  • Max object size: 256 key-value pairs

Fields§

§max_depth: Option<usize>

Maximum nesting depth for objects and arrays Set to None for unlimited depth (not recommended for embedded systems)

§max_string_length: Option<usize>

Maximum length of a string value in bytes Set to None for unlimited length (not recommended for embedded systems)

§max_array_size: Option<usize>

Maximum number of elements in an array Set to None for unlimited size (not recommended for embedded systems)

§max_object_size: Option<usize>

Maximum number of key-value pairs in an object Set to None for unlimited size (not recommended for embedded systems)

Implementations§

Source§

impl ParserConfig

Source

pub fn new() -> Self

Creates a new parser configuration with default limits suitable for embedded systems

Default limits:

  • Max depth: 32 levels
  • Max string length: 4096 bytes
  • Max array size: 1024 elements
  • Max object size: 256 key-value pairs
Examples found in repository?
examples/json_benchmarks.rs (line 151)
149fn bench_config_default() {
150    let json = r#"{"data":[1,2,3,4,5,6,7,8,9,10]}"#;
151    let config = ParserConfig::new();
152    let result = benchmark_parse_with_config("Parse with Default Config", json, &config, 30_000);
153    print_result(&result);
154}
More examples
Hide additional examples
examples/json_validation_demo.rs (line 56)
8fn main() {
9    println!("=== JSON Validation Demo ===\n");
10
11    // Example 1: Valid simple JSON
12    println!("1. Validating simple JSON:");
13    let json1 = br#"{"name": "Alice", "age": 30, "active": true}"#;
14    match validate_simple(json1) {
15        Ok(_) => println!("   ✓ Valid JSON\n"),
16        Err(e) => println!("   ✗ Invalid: {}\n", e),
17    }
18
19    // Example 2: Valid nested JSON
20    println!("2. Validating nested structure:");
21    let json2 = br#"{
22        "user": {
23            "name": "Bob",
24            "settings": {
25                "theme": "dark",
26                "notifications": true
27            }
28        },
29        "devices": ["phone", "tablet", "laptop"]
30    }"#;
31    match validate_simple(json2) {
32        Ok(_) => println!("   ✓ Valid JSON\n"),
33        Err(e) => println!("   ✗ Invalid: {}\n", e),
34    }
35
36    // Example 3: Invalid JSON - missing quote
37    println!("3. Detecting invalid JSON (missing quote):");
38    let json3 = br#"{"name: "Alice"}"#;
39    match validate_simple(json3) {
40        Ok(_) => println!("   ✓ Valid JSON\n"),
41        Err(e) => println!("   ✗ Invalid: {}\n", e),
42    }
43
44    // Example 4: Invalid JSON - trailing comma
45    println!("4. Detecting trailing comma:");
46    let json4 = br#"{"a": 1, "b": 2,}"#;
47    match validate_simple(json4) {
48        Ok(_) => println!("   ✓ Valid JSON\n"),
49        Err(e) => println!("   ✗ Invalid: {}\n", e),
50    }
51
52    // Example 5: Configuration limits - depth
53    println!("5. Checking depth limits:");
54    let deep_json = br#"{"a":{"b":{"c":{"d":{"e":1}}}}}"#;
55    let mut source = BufferSource::new(deep_json);
56    let shallow_config = ParserConfig::new().with_max_depth(Some(3));
57
58    match validate_json(&mut source, &shallow_config) {
59        Ok(_) => println!("   ✓ Within depth limit\n"),
60        Err(e) => println!("   ✗ Exceeds limit: {}\n", e),
61    }
62
63    // Example 6: Configuration limits - string length
64    println!("6. Checking string length limits:");
65    let long_string = format!(r#"{{"data": "{}"}}"#, "x".repeat(300));
66    let mut source = BufferSource::new(long_string.as_bytes());
67    let strict_config = ParserConfig::strict(); // max 256 bytes
68
69    match validate_json(&mut source, &strict_config) {
70        Ok(_) => println!("   ✓ Within string limit\n"),
71        Err(e) => println!("   ✗ Exceeds limit: {}\n", e),
72    }
73
74    // Example 7: Valid number formats
75    println!("7. Validating various number formats:");
76    let numbers: Vec<(&[u8], &str)> = vec![
77        (b"123", "integer"),
78        (b"-456", "negative"),
79        (b"3.14", "decimal"),
80        (b"1e10", "exponential"),
81        (b"2.5e-3", "scientific"),
82    ];
83
84    for (json, desc) in numbers {
85        let mut source = BufferSource::new(json);
86        let config = ParserConfig::new();
87        match validate_json(&mut source, &config) {
88            Ok(_) => println!("   ✓ {} ({})", std::str::from_utf8(json).unwrap(), desc),
89            Err(e) => println!("   ✗ {}: {}", desc, e),
90        }
91    }
92    println!();
93
94    // Example 8: Invalid number formats
95    println!("8. Detecting invalid numbers:");
96    let invalid_numbers: Vec<(&[u8], &str)> = vec![
97        (b"01", "leading zero"),
98        (b"-.5", "no digit before decimal"),
99        (b"1.", "no digit after decimal"),
100    ];
101
102    for (json, desc) in invalid_numbers {
103        let mut source = BufferSource::new(json);
104        let config = ParserConfig::new();
105        match validate_json(&mut source, &config) {
106            Ok(_) => println!("   ✗ Should have failed: {}", desc),
107            Err(e) => println!("   ✓ Correctly rejected {}: {}", desc, e),
108        }
109    }
110    println!();
111
112    // Example 9: Large array validation
113    println!("9. Validating array size limits:");
114    let large_array = format!(
115        "[{}]",
116        (0..100)
117            .map(|i| i.to_string())
118            .collect::<Vec<_>>()
119            .join(",")
120    );
121    let mut source = BufferSource::new(large_array.as_bytes());
122    let small_config = ParserConfig::strict().with_max_array_size(Some(50));
123
124    match validate_json(&mut source, &small_config) {
125        Ok(_) => println!("   ✓ Within array limit\n"),
126        Err(e) => println!("   ✗ Exceeds limit: {}\n", e),
127    }
128
129    // Example 10: Embedded use case - sensor data validation
130    println!("10. Embedded use case - validating sensor data:");
131    let sensor_readings: Vec<&[u8]> = vec![
132        br#"{"id":"temp_01","value":23.5,"ts":1234567890}"#.as_slice(),
133        br#"{"id":"hum_02","value":45.2,"ts":1234567891}"#.as_slice(),
134        br#"{"id":"bad","value":,"ts":123}"#.as_slice(), // Invalid
135    ];
136
137    let config = ParserConfig::strict();
138    for (i, reading) in sensor_readings.iter().enumerate() {
139        let mut source = BufferSource::new(*reading);
140        match validate_json(&mut source, &config) {
141            Ok(_) => println!("   ✓ Reading {} is valid", i + 1),
142            Err(e) => println!("   ✗ Reading {} invalid: {}", i + 1, e),
143        }
144    }
145
146    println!("\n=== Validation complete ===");
147}
148
149fn validate_simple(json: &[u8]) -> Result<(), String> {
150    let mut source = BufferSource::new(json);
151    let config = ParserConfig::new();
152    validate_json(&mut source, &config)
153}
examples/json_parser_config.rs (line 12)
7fn main() {
8    println!("=== JSON Parser Configuration Examples ===\n");
9
10    // Example 1: Default configuration (embedded-friendly)
11    println!("1. Default Configuration (embedded-friendly):");
12    let config = ParserConfig::new();
13    println!("   Max depth: {:?}", config.max_depth);
14    println!("   Max string length: {:?}", config.max_string_length);
15    println!("   Max array size: {:?}", config.max_array_size);
16    println!("   Max object size: {:?}", config.max_object_size);
17
18    let json = r#"{"name":"sensor","values":[1,2,3,4,5]}"#;
19    let mut source = BufferSource::new(json.as_bytes());
20    match parse_with_config(&mut source, &config) {
21        Ok(node) => println!("   ✓ Parsed successfully: {:?}\n", node),
22        Err(e) => println!("   ✗ Parse error: {}\n", e),
23    }
24
25    // Example 2: Strict configuration (highly constrained)
26    println!("2. Strict Configuration (ultra-low memory):");
27    let config = ParserConfig::strict();
28    println!("   Max depth: {:?}", config.max_depth);
29    println!("   Max string length: {:?}", config.max_string_length);
30    println!("   Max array size: {:?}", config.max_array_size);
31    println!("   Max object size: {:?}", config.max_object_size);
32
33    let json = r#"{"sensor":"temp","value":23.5}"#;
34    let mut source = BufferSource::new(json.as_bytes());
35    match parse_with_config(&mut source, &config) {
36        Ok(_node) => println!("   ✓ Parsed successfully\n"),
37        Err(e) => println!("   ✗ Parse error: {}\n", e),
38    }
39
40    // Example 3: Depth limit exceeded
41    println!("3. Demonstrating Depth Limit:");
42    let config = ParserConfig::new().with_max_depth(Some(3));
43    let deeply_nested = r#"{"a":{"b":{"c":{"d":1}}}}"#;
44    let mut source = BufferSource::new(deeply_nested.as_bytes());
45    match parse_with_config(&mut source, &config) {
46        Ok(_) => println!("   ✓ Parsed (unexpected)"),
47        Err(e) => println!("   ✗ Expected error: {}\n", e),
48    }
49
50    // Example 4: String length limit
51    println!("4. Demonstrating String Length Limit:");
52    let config = ParserConfig::new().with_max_string_length(Some(10));
53    let long_string = r#"{"key":"this is a very long string that exceeds the limit"}"#;
54    let mut source = BufferSource::new(long_string.as_bytes());
55    match parse_with_config(&mut source, &config) {
56        Ok(_) => println!("   ✓ Parsed (unexpected)"),
57        Err(e) => println!("   ✗ Expected error: {}\n", e),
58    }
59
60    // Example 5: Array size limit
61    println!("5. Demonstrating Array Size Limit:");
62    let config = ParserConfig::new().with_max_array_size(Some(5));
63    let large_array = r#"[1,2,3,4,5,6,7,8,9,10]"#;
64    let mut source = BufferSource::new(large_array.as_bytes());
65    match parse_with_config(&mut source, &config) {
66        Ok(_) => println!("   ✓ Parsed (unexpected)"),
67        Err(e) => println!("   ✗ Expected error: {}\n", e),
68    }
69
70    // Example 6: Object size limit
71    println!("6. Demonstrating Object Size Limit:");
72    let config = ParserConfig::new().with_max_object_size(Some(2));
73    let large_object = r#"{"a":1,"b":2,"c":3,"d":4}"#;
74    let mut source = BufferSource::new(large_object.as_bytes());
75    match parse_with_config(&mut source, &config) {
76        Ok(_) => println!("   ✓ Parsed (unexpected)"),
77        Err(e) => println!("   ✗ Expected error: {}\n", e),
78    }
79
80    // Example 7: Custom configuration for specific use case
81    println!("7. Custom Configuration (IoT sensor data):");
82    let config = ParserConfig::new()
83        .with_max_depth(Some(4)) // Sensor data rarely deeply nested
84        .with_max_string_length(Some(64)) // Short identifiers
85        .with_max_array_size(Some(100)) // Moderate sensor readings
86        .with_max_object_size(Some(20)); // Few fields per reading
87
88    let sensor_data = r#"{
89        "device": "temp_sensor_01",
90        "timestamp": 1699876543,
91        "readings": [
92            {"temp": 23.5, "humidity": 45.2},
93            {"temp": 23.7, "humidity": 45.1}
94        ]
95    }"#;
96    let mut source = BufferSource::new(sensor_data.as_bytes());
97    match parse_with_config(&mut source, &config) {
98        Ok(node) => {
99            println!("   ✓ Parsed sensor data successfully");
100
101            // Demonstrate safe access methods
102            if let Some(device) = node.get("device").and_then(|n| n.as_str()) {
103                println!("   Device: {}", device);
104            }
105
106            if let Some(readings) = node.get("readings").and_then(|n| n.as_array()) {
107                println!("   Readings count: {}", readings.len());
108
109                // Use safe array access
110                if let Some(first) = readings.first() {
111                    if let Some(temp) = first.get("temp") {
112                        println!("   First reading temperature: {:?}", temp);
113                    }
114                }
115            }
116            println!();
117        }
118        Err(e) => println!("   ✗ Parse error: {}\n", e),
119    }
120
121    // Example 8: Unlimited configuration (not recommended for embedded)
122    println!("8. Unlimited Configuration (desktop/server use):");
123    let config = ParserConfig::unlimited();
124    println!("   Max depth: {:?}", config.max_depth);
125    println!("   Max string length: {:?}", config.max_string_length);
126    println!("   WARNING: Not recommended for embedded systems!");
127    println!("   Use this only on systems with abundant memory.\n");
128
129    // Example 9: Memory usage estimation
130    println!("9. Memory Usage Estimation:");
131    println!(
132        "   Node enum size: {} bytes",
133        std::mem::size_of::<babbel_json::Node>()
134    );
135    println!("   With strict config:");
136    println!("     Max string: 256 bytes");
137    println!("     Max array: 64 × 56 bytes = 3,584 bytes");
138    println!("     Max object: 32 × 80 bytes ≈ 2,560 bytes");
139    println!("     Per level: ~6.4 KB");
140    println!("     Total (16 levels): ~102 KB");
141    println!();
142
143    println!("   With default config:");
144    println!("     Max string: 4,096 bytes");
145    println!("     Max array: 1,024 × 56 bytes = 57,344 bytes");
146    println!("     Max object: 256 × 80 bytes ≈ 20,480 bytes");
147    println!("     Per level: ~81.9 KB");
148    println!("     Total (32 levels): ~2.6 MB");
149    println!();
150
151    println!("=== Recommendations for Different Platforms ===\n");
152
153    println!("Ultra-Low Memory (<16KB RAM):");
154    println!("  ParserConfig::strict().with_max_depth(Some(8))");
155    println!();
156
157    println!("Low Memory (16-64KB RAM):");
158    println!("  ParserConfig::strict()");
159    println!();
160
161    println!("Medium Memory (64-256KB RAM):");
162    println!("  ParserConfig::new().with_max_depth(Some(16))");
163    println!();
164
165    println!("Higher Memory (>256KB RAM):");
166    println!("  ParserConfig::new() // Use defaults");
167    println!();
168}
Source

pub fn unlimited() -> Self

Creates a configuration with no limits (uses default behavior)

Warning: This is not recommended for embedded systems as it can lead to stack overflow or excessive memory consumption

Examples found in repository?
examples/json_benchmarks.rs (line 167)
165fn bench_config_unlimited() {
166    let json = r#"{"data":[1,2,3,4,5,6,7,8,9,10]}"#;
167    let config = ParserConfig::unlimited();
168    let result = benchmark_parse_with_config("Parse with Unlimited Config", json, &config, 30_000);
169    print_result(&result);
170}
More examples
Hide additional examples
examples/json_parser_config.rs (line 123)
7fn main() {
8    println!("=== JSON Parser Configuration Examples ===\n");
9
10    // Example 1: Default configuration (embedded-friendly)
11    println!("1. Default Configuration (embedded-friendly):");
12    let config = ParserConfig::new();
13    println!("   Max depth: {:?}", config.max_depth);
14    println!("   Max string length: {:?}", config.max_string_length);
15    println!("   Max array size: {:?}", config.max_array_size);
16    println!("   Max object size: {:?}", config.max_object_size);
17
18    let json = r#"{"name":"sensor","values":[1,2,3,4,5]}"#;
19    let mut source = BufferSource::new(json.as_bytes());
20    match parse_with_config(&mut source, &config) {
21        Ok(node) => println!("   ✓ Parsed successfully: {:?}\n", node),
22        Err(e) => println!("   ✗ Parse error: {}\n", e),
23    }
24
25    // Example 2: Strict configuration (highly constrained)
26    println!("2. Strict Configuration (ultra-low memory):");
27    let config = ParserConfig::strict();
28    println!("   Max depth: {:?}", config.max_depth);
29    println!("   Max string length: {:?}", config.max_string_length);
30    println!("   Max array size: {:?}", config.max_array_size);
31    println!("   Max object size: {:?}", config.max_object_size);
32
33    let json = r#"{"sensor":"temp","value":23.5}"#;
34    let mut source = BufferSource::new(json.as_bytes());
35    match parse_with_config(&mut source, &config) {
36        Ok(_node) => println!("   ✓ Parsed successfully\n"),
37        Err(e) => println!("   ✗ Parse error: {}\n", e),
38    }
39
40    // Example 3: Depth limit exceeded
41    println!("3. Demonstrating Depth Limit:");
42    let config = ParserConfig::new().with_max_depth(Some(3));
43    let deeply_nested = r#"{"a":{"b":{"c":{"d":1}}}}"#;
44    let mut source = BufferSource::new(deeply_nested.as_bytes());
45    match parse_with_config(&mut source, &config) {
46        Ok(_) => println!("   ✓ Parsed (unexpected)"),
47        Err(e) => println!("   ✗ Expected error: {}\n", e),
48    }
49
50    // Example 4: String length limit
51    println!("4. Demonstrating String Length Limit:");
52    let config = ParserConfig::new().with_max_string_length(Some(10));
53    let long_string = r#"{"key":"this is a very long string that exceeds the limit"}"#;
54    let mut source = BufferSource::new(long_string.as_bytes());
55    match parse_with_config(&mut source, &config) {
56        Ok(_) => println!("   ✓ Parsed (unexpected)"),
57        Err(e) => println!("   ✗ Expected error: {}\n", e),
58    }
59
60    // Example 5: Array size limit
61    println!("5. Demonstrating Array Size Limit:");
62    let config = ParserConfig::new().with_max_array_size(Some(5));
63    let large_array = r#"[1,2,3,4,5,6,7,8,9,10]"#;
64    let mut source = BufferSource::new(large_array.as_bytes());
65    match parse_with_config(&mut source, &config) {
66        Ok(_) => println!("   ✓ Parsed (unexpected)"),
67        Err(e) => println!("   ✗ Expected error: {}\n", e),
68    }
69
70    // Example 6: Object size limit
71    println!("6. Demonstrating Object Size Limit:");
72    let config = ParserConfig::new().with_max_object_size(Some(2));
73    let large_object = r#"{"a":1,"b":2,"c":3,"d":4}"#;
74    let mut source = BufferSource::new(large_object.as_bytes());
75    match parse_with_config(&mut source, &config) {
76        Ok(_) => println!("   ✓ Parsed (unexpected)"),
77        Err(e) => println!("   ✗ Expected error: {}\n", e),
78    }
79
80    // Example 7: Custom configuration for specific use case
81    println!("7. Custom Configuration (IoT sensor data):");
82    let config = ParserConfig::new()
83        .with_max_depth(Some(4)) // Sensor data rarely deeply nested
84        .with_max_string_length(Some(64)) // Short identifiers
85        .with_max_array_size(Some(100)) // Moderate sensor readings
86        .with_max_object_size(Some(20)); // Few fields per reading
87
88    let sensor_data = r#"{
89        "device": "temp_sensor_01",
90        "timestamp": 1699876543,
91        "readings": [
92            {"temp": 23.5, "humidity": 45.2},
93            {"temp": 23.7, "humidity": 45.1}
94        ]
95    }"#;
96    let mut source = BufferSource::new(sensor_data.as_bytes());
97    match parse_with_config(&mut source, &config) {
98        Ok(node) => {
99            println!("   ✓ Parsed sensor data successfully");
100
101            // Demonstrate safe access methods
102            if let Some(device) = node.get("device").and_then(|n| n.as_str()) {
103                println!("   Device: {}", device);
104            }
105
106            if let Some(readings) = node.get("readings").and_then(|n| n.as_array()) {
107                println!("   Readings count: {}", readings.len());
108
109                // Use safe array access
110                if let Some(first) = readings.first() {
111                    if let Some(temp) = first.get("temp") {
112                        println!("   First reading temperature: {:?}", temp);
113                    }
114                }
115            }
116            println!();
117        }
118        Err(e) => println!("   ✗ Parse error: {}\n", e),
119    }
120
121    // Example 8: Unlimited configuration (not recommended for embedded)
122    println!("8. Unlimited Configuration (desktop/server use):");
123    let config = ParserConfig::unlimited();
124    println!("   Max depth: {:?}", config.max_depth);
125    println!("   Max string length: {:?}", config.max_string_length);
126    println!("   WARNING: Not recommended for embedded systems!");
127    println!("   Use this only on systems with abundant memory.\n");
128
129    // Example 9: Memory usage estimation
130    println!("9. Memory Usage Estimation:");
131    println!(
132        "   Node enum size: {} bytes",
133        std::mem::size_of::<babbel_json::Node>()
134    );
135    println!("   With strict config:");
136    println!("     Max string: 256 bytes");
137    println!("     Max array: 64 × 56 bytes = 3,584 bytes");
138    println!("     Max object: 32 × 80 bytes ≈ 2,560 bytes");
139    println!("     Per level: ~6.4 KB");
140    println!("     Total (16 levels): ~102 KB");
141    println!();
142
143    println!("   With default config:");
144    println!("     Max string: 4,096 bytes");
145    println!("     Max array: 1,024 × 56 bytes = 57,344 bytes");
146    println!("     Max object: 256 × 80 bytes ≈ 20,480 bytes");
147    println!("     Per level: ~81.9 KB");
148    println!("     Total (32 levels): ~2.6 MB");
149    println!();
150
151    println!("=== Recommendations for Different Platforms ===\n");
152
153    println!("Ultra-Low Memory (<16KB RAM):");
154    println!("  ParserConfig::strict().with_max_depth(Some(8))");
155    println!();
156
157    println!("Low Memory (16-64KB RAM):");
158    println!("  ParserConfig::strict()");
159    println!();
160
161    println!("Medium Memory (64-256KB RAM):");
162    println!("  ParserConfig::new().with_max_depth(Some(16))");
163    println!();
164
165    println!("Higher Memory (>256KB RAM):");
166    println!("  ParserConfig::new() // Use defaults");
167    println!();
168}
Source

pub fn strict() -> Self

Creates a very strict configuration for highly constrained embedded systems

Strict limits:

  • Max depth: 16 levels
  • Max string length: 256 bytes
  • Max array size: 64 elements
  • Max object size: 32 key-value pairs
Examples found in repository?
examples/json_embedded.rs (line 32)
30pub fn test_parsing() {
31    let json = br#"{"id":"sensor_01","value":23.5}"#;
32    let config = ParserConfig::strict();
33    let mut source = BufferSource::new(json);
34    let _ = parse_with_config(&mut source, &config);
35}
More examples
Hide additional examples
examples/json_benchmarks.rs (line 159)
157fn bench_config_strict() {
158    let json = r#"{"data":[1,2,3,4,5,6,7,8,9,10]}"#;
159    let config = ParserConfig::strict();
160    let result = benchmark_parse_with_config("Parse with Strict Config", json, &config, 30_000);
161    print_result(&result);
162}
examples/json_validation_demo.rs (line 67)
8fn main() {
9    println!("=== JSON Validation Demo ===\n");
10
11    // Example 1: Valid simple JSON
12    println!("1. Validating simple JSON:");
13    let json1 = br#"{"name": "Alice", "age": 30, "active": true}"#;
14    match validate_simple(json1) {
15        Ok(_) => println!("   ✓ Valid JSON\n"),
16        Err(e) => println!("   ✗ Invalid: {}\n", e),
17    }
18
19    // Example 2: Valid nested JSON
20    println!("2. Validating nested structure:");
21    let json2 = br#"{
22        "user": {
23            "name": "Bob",
24            "settings": {
25                "theme": "dark",
26                "notifications": true
27            }
28        },
29        "devices": ["phone", "tablet", "laptop"]
30    }"#;
31    match validate_simple(json2) {
32        Ok(_) => println!("   ✓ Valid JSON\n"),
33        Err(e) => println!("   ✗ Invalid: {}\n", e),
34    }
35
36    // Example 3: Invalid JSON - missing quote
37    println!("3. Detecting invalid JSON (missing quote):");
38    let json3 = br#"{"name: "Alice"}"#;
39    match validate_simple(json3) {
40        Ok(_) => println!("   ✓ Valid JSON\n"),
41        Err(e) => println!("   ✗ Invalid: {}\n", e),
42    }
43
44    // Example 4: Invalid JSON - trailing comma
45    println!("4. Detecting trailing comma:");
46    let json4 = br#"{"a": 1, "b": 2,}"#;
47    match validate_simple(json4) {
48        Ok(_) => println!("   ✓ Valid JSON\n"),
49        Err(e) => println!("   ✗ Invalid: {}\n", e),
50    }
51
52    // Example 5: Configuration limits - depth
53    println!("5. Checking depth limits:");
54    let deep_json = br#"{"a":{"b":{"c":{"d":{"e":1}}}}}"#;
55    let mut source = BufferSource::new(deep_json);
56    let shallow_config = ParserConfig::new().with_max_depth(Some(3));
57
58    match validate_json(&mut source, &shallow_config) {
59        Ok(_) => println!("   ✓ Within depth limit\n"),
60        Err(e) => println!("   ✗ Exceeds limit: {}\n", e),
61    }
62
63    // Example 6: Configuration limits - string length
64    println!("6. Checking string length limits:");
65    let long_string = format!(r#"{{"data": "{}"}}"#, "x".repeat(300));
66    let mut source = BufferSource::new(long_string.as_bytes());
67    let strict_config = ParserConfig::strict(); // max 256 bytes
68
69    match validate_json(&mut source, &strict_config) {
70        Ok(_) => println!("   ✓ Within string limit\n"),
71        Err(e) => println!("   ✗ Exceeds limit: {}\n", e),
72    }
73
74    // Example 7: Valid number formats
75    println!("7. Validating various number formats:");
76    let numbers: Vec<(&[u8], &str)> = vec![
77        (b"123", "integer"),
78        (b"-456", "negative"),
79        (b"3.14", "decimal"),
80        (b"1e10", "exponential"),
81        (b"2.5e-3", "scientific"),
82    ];
83
84    for (json, desc) in numbers {
85        let mut source = BufferSource::new(json);
86        let config = ParserConfig::new();
87        match validate_json(&mut source, &config) {
88            Ok(_) => println!("   ✓ {} ({})", std::str::from_utf8(json).unwrap(), desc),
89            Err(e) => println!("   ✗ {}: {}", desc, e),
90        }
91    }
92    println!();
93
94    // Example 8: Invalid number formats
95    println!("8. Detecting invalid numbers:");
96    let invalid_numbers: Vec<(&[u8], &str)> = vec![
97        (b"01", "leading zero"),
98        (b"-.5", "no digit before decimal"),
99        (b"1.", "no digit after decimal"),
100    ];
101
102    for (json, desc) in invalid_numbers {
103        let mut source = BufferSource::new(json);
104        let config = ParserConfig::new();
105        match validate_json(&mut source, &config) {
106            Ok(_) => println!("   ✗ Should have failed: {}", desc),
107            Err(e) => println!("   ✓ Correctly rejected {}: {}", desc, e),
108        }
109    }
110    println!();
111
112    // Example 9: Large array validation
113    println!("9. Validating array size limits:");
114    let large_array = format!(
115        "[{}]",
116        (0..100)
117            .map(|i| i.to_string())
118            .collect::<Vec<_>>()
119            .join(",")
120    );
121    let mut source = BufferSource::new(large_array.as_bytes());
122    let small_config = ParserConfig::strict().with_max_array_size(Some(50));
123
124    match validate_json(&mut source, &small_config) {
125        Ok(_) => println!("   ✓ Within array limit\n"),
126        Err(e) => println!("   ✗ Exceeds limit: {}\n", e),
127    }
128
129    // Example 10: Embedded use case - sensor data validation
130    println!("10. Embedded use case - validating sensor data:");
131    let sensor_readings: Vec<&[u8]> = vec![
132        br#"{"id":"temp_01","value":23.5,"ts":1234567890}"#.as_slice(),
133        br#"{"id":"hum_02","value":45.2,"ts":1234567891}"#.as_slice(),
134        br#"{"id":"bad","value":,"ts":123}"#.as_slice(), // Invalid
135    ];
136
137    let config = ParserConfig::strict();
138    for (i, reading) in sensor_readings.iter().enumerate() {
139        let mut source = BufferSource::new(*reading);
140        match validate_json(&mut source, &config) {
141            Ok(_) => println!("   ✓ Reading {} is valid", i + 1),
142            Err(e) => println!("   ✗ Reading {} invalid: {}", i + 1, e),
143        }
144    }
145
146    println!("\n=== Validation complete ===");
147}
examples/json_iot_sensor.rs (line 93)
15fn main() {
16    println!("=== Embedded IoT Sensor Example ===\n");
17
18    // Example 1: Simple temperature sensor reading
19    println!("1. Simple Sensor Reading:");
20    let temp_reading = sensor::simple_reading("temp_sensor_01", 23.5, 1699876543);
21    print_json("Temperature Reading", &temp_reading);
22
23    // Example 2: Multi-value environmental sensor
24    println!("\n2. Multi-Value Sensor Reading:");
25    let env_values = vec![
26        ("temperature", 23.5),
27        ("humidity", 45.2),
28        ("pressure", 1013.25),
29    ];
30    let env_reading = sensor::multi_reading("env_sensor_01", &env_values, 1699876543);
31    print_json("Environmental Reading", &env_reading);
32
33    // Example 3: Batch sensor readings (efficient for low-power transmission)
34    println!("\n3. Batched Sensor Readings:");
35    let readings = vec![
36        sensor::simple_reading("temp_01", 23.5, 1699876543),
37        sensor::simple_reading("temp_01", 23.7, 1699876563),
38        sensor::simple_reading("temp_01", 23.4, 1699876583),
39    ];
40    let batch = sensor::batch_readings("temp_01", readings);
41    print_json("Batch of Readings", &batch);
42
43    // Example 4: Memory-efficient construction
44    println!("\n4. Memory-Efficient Construction:");
45    let reading = ObjectBuilder::with_capacity(4)
46        .add_str("device", "motion_01")
47        .add_bool("detected", true)
48        .add_i64("timestamp", 1699876543)
49        .add_u32("count", 5)
50        .build();
51
52    let size = memory::estimate_node_size(&reading);
53    println!("   Estimated memory: {} bytes", size);
54    print_json("Motion Detection", &reading);
55
56    // Example 5: Configuration management
57    println!("\n5. Device Configuration:");
58    let device_config = config::simple()
59        .add_str("wifi_ssid", "IoT_Network")
60        .add_str("mqtt_broker", "192.168.1.100")
61        .add_i32("sample_interval_ms", 5000)
62        .add_i32("transmit_interval_ms", 60000)
63        .add_bool("deep_sleep_enabled", true)
64        .add_f64("temperature_threshold", 30.0)
65        .build();
66
67    print_json("Device Config", &device_config);
68
69    // Read configuration values safely
70    println!("\n   Reading config values:");
71    if let Some(ssid) = config::get_string(&device_config, "wifi_ssid") {
72        println!("   WiFi SSID: {}", ssid);
73    }
74    if let Some(interval) = config::get_i32(&device_config, "sample_interval_ms") {
75        println!("   Sample Interval: {}ms", interval);
76    }
77    if let Some(deep_sleep) = config::get_bool(&device_config, "deep_sleep_enabled") {
78        println!("   Deep Sleep: {}", deep_sleep);
79    }
80
81    // Example 6: Parsing with memory limits (for constrained devices)
82    println!("\n6. Parsing with Memory Limits:");
83    let json_config = r#"{
84        "device_id": "sensor_01",
85        "location": "room_A",
86        "enabled": true,
87        "thresholds": {
88            "min": 15.0,
89            "max": 30.0
90        }
91    }"#;
92
93    let config = ParserConfig::strict();
94    let mut source = BufferSource::new(json_config.as_bytes());
95
96    match parse_with_config(&mut source, &config) {
97        Ok(parsed) => {
98            println!("   ✓ Parsed configuration successfully");
99
100            if let Some(device_id) = config::get_string(&parsed, "device_id") {
101                println!("   Device ID: {}", device_id);
102            }
103
104            if let Some(thresholds) = parsed.get("thresholds") {
105                if let Some(min) = config::get_f64(thresholds, "min") {
106                    println!("   Min Threshold: {}", min);
107                }
108                if let Some(max) = config::get_f64(thresholds, "max") {
109                    println!("   Max Threshold: {}", max);
110                }
111            }
112        }
113        Err(e) => println!("   ✗ Parse error: {}", e),
114    }
115
116    // Example 7: Array of sensor data
117    println!("\n7. Sensor Data Array:");
118    let sensor_array = ArrayBuilder::with_capacity(5)
119        .add_f64(23.5)
120        .add_f64(23.7)
121        .add_f64(23.4)
122        .add_f64(23.6)
123        .add_f64(23.8)
124        .build();
125
126    print_json("Temperature History", &sensor_array);
127
128    // Example 8: Complex sensor payload
129    println!("\n8. Complex Sensor Payload:");
130    let mut status_map = std::collections::HashMap::new();
131    status_map.insert("battery".to_string(), Node::Number(Numeric::UInt32(87)));
132    status_map.insert(
133        "signal_strength".to_string(),
134        Node::Number(Numeric::Int32(-65)),
135    );
136    status_map.insert("uptime".to_string(), Node::Number(Numeric::UInt32(3600)));
137
138    let payload = ObjectBuilder::new()
139        .add_str("device", "multi_sensor_01")
140        .add_i64("timestamp", 1699876543)
141        .add_object("status", status_map)
142        .add_node("reading", sensor::simple_reading("temp", 24.1, 1699876543))
143        .build();
144
145    let size = memory::estimate_node_size(&payload);
146    println!("   Payload size: {} bytes", size);
147    print_json("Complex Payload", &payload);
148
149    // Example 9: Calculating memory requirements
150    println!("\n9. Memory Requirements Analysis:");
151    println!("   Node size: {} bytes", memory::node_size());
152    println!("   Numeric size: {} bytes", memory::numeric_size());
153
154    let simple = sensor::simple_reading("test", 1.0, 0);
155    println!(
156        "   Simple reading: {} bytes",
157        memory::estimate_node_size(&simple)
158    );
159
160    let multi = sensor::multi_reading("test", &[("a", 1.0), ("b", 2.0)], 0);
161    println!(
162        "   Multi reading: {} bytes",
163        memory::estimate_node_size(&multi)
164    );
165
166    println!("\n=== Memory Optimization Tips ===");
167    println!("1. Use with_capacity() when size is known");
168    println!("2. Reuse buffers when possible");
169    println!("3. Use ParserConfig::strict() for constrained devices");
170    println!("4. Batch readings to reduce overhead");
171    println!("5. Choose appropriate numeric types (i32 vs i64)");
172}
examples/json_parser_config.rs (line 27)
7fn main() {
8    println!("=== JSON Parser Configuration Examples ===\n");
9
10    // Example 1: Default configuration (embedded-friendly)
11    println!("1. Default Configuration (embedded-friendly):");
12    let config = ParserConfig::new();
13    println!("   Max depth: {:?}", config.max_depth);
14    println!("   Max string length: {:?}", config.max_string_length);
15    println!("   Max array size: {:?}", config.max_array_size);
16    println!("   Max object size: {:?}", config.max_object_size);
17
18    let json = r#"{"name":"sensor","values":[1,2,3,4,5]}"#;
19    let mut source = BufferSource::new(json.as_bytes());
20    match parse_with_config(&mut source, &config) {
21        Ok(node) => println!("   ✓ Parsed successfully: {:?}\n", node),
22        Err(e) => println!("   ✗ Parse error: {}\n", e),
23    }
24
25    // Example 2: Strict configuration (highly constrained)
26    println!("2. Strict Configuration (ultra-low memory):");
27    let config = ParserConfig::strict();
28    println!("   Max depth: {:?}", config.max_depth);
29    println!("   Max string length: {:?}", config.max_string_length);
30    println!("   Max array size: {:?}", config.max_array_size);
31    println!("   Max object size: {:?}", config.max_object_size);
32
33    let json = r#"{"sensor":"temp","value":23.5}"#;
34    let mut source = BufferSource::new(json.as_bytes());
35    match parse_with_config(&mut source, &config) {
36        Ok(_node) => println!("   ✓ Parsed successfully\n"),
37        Err(e) => println!("   ✗ Parse error: {}\n", e),
38    }
39
40    // Example 3: Depth limit exceeded
41    println!("3. Demonstrating Depth Limit:");
42    let config = ParserConfig::new().with_max_depth(Some(3));
43    let deeply_nested = r#"{"a":{"b":{"c":{"d":1}}}}"#;
44    let mut source = BufferSource::new(deeply_nested.as_bytes());
45    match parse_with_config(&mut source, &config) {
46        Ok(_) => println!("   ✓ Parsed (unexpected)"),
47        Err(e) => println!("   ✗ Expected error: {}\n", e),
48    }
49
50    // Example 4: String length limit
51    println!("4. Demonstrating String Length Limit:");
52    let config = ParserConfig::new().with_max_string_length(Some(10));
53    let long_string = r#"{"key":"this is a very long string that exceeds the limit"}"#;
54    let mut source = BufferSource::new(long_string.as_bytes());
55    match parse_with_config(&mut source, &config) {
56        Ok(_) => println!("   ✓ Parsed (unexpected)"),
57        Err(e) => println!("   ✗ Expected error: {}\n", e),
58    }
59
60    // Example 5: Array size limit
61    println!("5. Demonstrating Array Size Limit:");
62    let config = ParserConfig::new().with_max_array_size(Some(5));
63    let large_array = r#"[1,2,3,4,5,6,7,8,9,10]"#;
64    let mut source = BufferSource::new(large_array.as_bytes());
65    match parse_with_config(&mut source, &config) {
66        Ok(_) => println!("   ✓ Parsed (unexpected)"),
67        Err(e) => println!("   ✗ Expected error: {}\n", e),
68    }
69
70    // Example 6: Object size limit
71    println!("6. Demonstrating Object Size Limit:");
72    let config = ParserConfig::new().with_max_object_size(Some(2));
73    let large_object = r#"{"a":1,"b":2,"c":3,"d":4}"#;
74    let mut source = BufferSource::new(large_object.as_bytes());
75    match parse_with_config(&mut source, &config) {
76        Ok(_) => println!("   ✓ Parsed (unexpected)"),
77        Err(e) => println!("   ✗ Expected error: {}\n", e),
78    }
79
80    // Example 7: Custom configuration for specific use case
81    println!("7. Custom Configuration (IoT sensor data):");
82    let config = ParserConfig::new()
83        .with_max_depth(Some(4)) // Sensor data rarely deeply nested
84        .with_max_string_length(Some(64)) // Short identifiers
85        .with_max_array_size(Some(100)) // Moderate sensor readings
86        .with_max_object_size(Some(20)); // Few fields per reading
87
88    let sensor_data = r#"{
89        "device": "temp_sensor_01",
90        "timestamp": 1699876543,
91        "readings": [
92            {"temp": 23.5, "humidity": 45.2},
93            {"temp": 23.7, "humidity": 45.1}
94        ]
95    }"#;
96    let mut source = BufferSource::new(sensor_data.as_bytes());
97    match parse_with_config(&mut source, &config) {
98        Ok(node) => {
99            println!("   ✓ Parsed sensor data successfully");
100
101            // Demonstrate safe access methods
102            if let Some(device) = node.get("device").and_then(|n| n.as_str()) {
103                println!("   Device: {}", device);
104            }
105
106            if let Some(readings) = node.get("readings").and_then(|n| n.as_array()) {
107                println!("   Readings count: {}", readings.len());
108
109                // Use safe array access
110                if let Some(first) = readings.first() {
111                    if let Some(temp) = first.get("temp") {
112                        println!("   First reading temperature: {:?}", temp);
113                    }
114                }
115            }
116            println!();
117        }
118        Err(e) => println!("   ✗ Parse error: {}\n", e),
119    }
120
121    // Example 8: Unlimited configuration (not recommended for embedded)
122    println!("8. Unlimited Configuration (desktop/server use):");
123    let config = ParserConfig::unlimited();
124    println!("   Max depth: {:?}", config.max_depth);
125    println!("   Max string length: {:?}", config.max_string_length);
126    println!("   WARNING: Not recommended for embedded systems!");
127    println!("   Use this only on systems with abundant memory.\n");
128
129    // Example 9: Memory usage estimation
130    println!("9. Memory Usage Estimation:");
131    println!(
132        "   Node enum size: {} bytes",
133        std::mem::size_of::<babbel_json::Node>()
134    );
135    println!("   With strict config:");
136    println!("     Max string: 256 bytes");
137    println!("     Max array: 64 × 56 bytes = 3,584 bytes");
138    println!("     Max object: 32 × 80 bytes ≈ 2,560 bytes");
139    println!("     Per level: ~6.4 KB");
140    println!("     Total (16 levels): ~102 KB");
141    println!();
142
143    println!("   With default config:");
144    println!("     Max string: 4,096 bytes");
145    println!("     Max array: 1,024 × 56 bytes = 57,344 bytes");
146    println!("     Max object: 256 × 80 bytes ≈ 20,480 bytes");
147    println!("     Per level: ~81.9 KB");
148    println!("     Total (32 levels): ~2.6 MB");
149    println!();
150
151    println!("=== Recommendations for Different Platforms ===\n");
152
153    println!("Ultra-Low Memory (<16KB RAM):");
154    println!("  ParserConfig::strict().with_max_depth(Some(8))");
155    println!();
156
157    println!("Low Memory (16-64KB RAM):");
158    println!("  ParserConfig::strict()");
159    println!();
160
161    println!("Medium Memory (64-256KB RAM):");
162    println!("  ParserConfig::new().with_max_depth(Some(16))");
163    println!();
164
165    println!("Higher Memory (>256KB RAM):");
166    println!("  ParserConfig::new() // Use defaults");
167    println!();
168}
Source

pub fn with_max_depth(self, max_depth: Option<usize>) -> Self

Sets the maximum nesting depth

Examples found in repository?
examples/json_validation_demo.rs (line 56)
8fn main() {
9    println!("=== JSON Validation Demo ===\n");
10
11    // Example 1: Valid simple JSON
12    println!("1. Validating simple JSON:");
13    let json1 = br#"{"name": "Alice", "age": 30, "active": true}"#;
14    match validate_simple(json1) {
15        Ok(_) => println!("   ✓ Valid JSON\n"),
16        Err(e) => println!("   ✗ Invalid: {}\n", e),
17    }
18
19    // Example 2: Valid nested JSON
20    println!("2. Validating nested structure:");
21    let json2 = br#"{
22        "user": {
23            "name": "Bob",
24            "settings": {
25                "theme": "dark",
26                "notifications": true
27            }
28        },
29        "devices": ["phone", "tablet", "laptop"]
30    }"#;
31    match validate_simple(json2) {
32        Ok(_) => println!("   ✓ Valid JSON\n"),
33        Err(e) => println!("   ✗ Invalid: {}\n", e),
34    }
35
36    // Example 3: Invalid JSON - missing quote
37    println!("3. Detecting invalid JSON (missing quote):");
38    let json3 = br#"{"name: "Alice"}"#;
39    match validate_simple(json3) {
40        Ok(_) => println!("   ✓ Valid JSON\n"),
41        Err(e) => println!("   ✗ Invalid: {}\n", e),
42    }
43
44    // Example 4: Invalid JSON - trailing comma
45    println!("4. Detecting trailing comma:");
46    let json4 = br#"{"a": 1, "b": 2,}"#;
47    match validate_simple(json4) {
48        Ok(_) => println!("   ✓ Valid JSON\n"),
49        Err(e) => println!("   ✗ Invalid: {}\n", e),
50    }
51
52    // Example 5: Configuration limits - depth
53    println!("5. Checking depth limits:");
54    let deep_json = br#"{"a":{"b":{"c":{"d":{"e":1}}}}}"#;
55    let mut source = BufferSource::new(deep_json);
56    let shallow_config = ParserConfig::new().with_max_depth(Some(3));
57
58    match validate_json(&mut source, &shallow_config) {
59        Ok(_) => println!("   ✓ Within depth limit\n"),
60        Err(e) => println!("   ✗ Exceeds limit: {}\n", e),
61    }
62
63    // Example 6: Configuration limits - string length
64    println!("6. Checking string length limits:");
65    let long_string = format!(r#"{{"data": "{}"}}"#, "x".repeat(300));
66    let mut source = BufferSource::new(long_string.as_bytes());
67    let strict_config = ParserConfig::strict(); // max 256 bytes
68
69    match validate_json(&mut source, &strict_config) {
70        Ok(_) => println!("   ✓ Within string limit\n"),
71        Err(e) => println!("   ✗ Exceeds limit: {}\n", e),
72    }
73
74    // Example 7: Valid number formats
75    println!("7. Validating various number formats:");
76    let numbers: Vec<(&[u8], &str)> = vec![
77        (b"123", "integer"),
78        (b"-456", "negative"),
79        (b"3.14", "decimal"),
80        (b"1e10", "exponential"),
81        (b"2.5e-3", "scientific"),
82    ];
83
84    for (json, desc) in numbers {
85        let mut source = BufferSource::new(json);
86        let config = ParserConfig::new();
87        match validate_json(&mut source, &config) {
88            Ok(_) => println!("   ✓ {} ({})", std::str::from_utf8(json).unwrap(), desc),
89            Err(e) => println!("   ✗ {}: {}", desc, e),
90        }
91    }
92    println!();
93
94    // Example 8: Invalid number formats
95    println!("8. Detecting invalid numbers:");
96    let invalid_numbers: Vec<(&[u8], &str)> = vec![
97        (b"01", "leading zero"),
98        (b"-.5", "no digit before decimal"),
99        (b"1.", "no digit after decimal"),
100    ];
101
102    for (json, desc) in invalid_numbers {
103        let mut source = BufferSource::new(json);
104        let config = ParserConfig::new();
105        match validate_json(&mut source, &config) {
106            Ok(_) => println!("   ✗ Should have failed: {}", desc),
107            Err(e) => println!("   ✓ Correctly rejected {}: {}", desc, e),
108        }
109    }
110    println!();
111
112    // Example 9: Large array validation
113    println!("9. Validating array size limits:");
114    let large_array = format!(
115        "[{}]",
116        (0..100)
117            .map(|i| i.to_string())
118            .collect::<Vec<_>>()
119            .join(",")
120    );
121    let mut source = BufferSource::new(large_array.as_bytes());
122    let small_config = ParserConfig::strict().with_max_array_size(Some(50));
123
124    match validate_json(&mut source, &small_config) {
125        Ok(_) => println!("   ✓ Within array limit\n"),
126        Err(e) => println!("   ✗ Exceeds limit: {}\n", e),
127    }
128
129    // Example 10: Embedded use case - sensor data validation
130    println!("10. Embedded use case - validating sensor data:");
131    let sensor_readings: Vec<&[u8]> = vec![
132        br#"{"id":"temp_01","value":23.5,"ts":1234567890}"#.as_slice(),
133        br#"{"id":"hum_02","value":45.2,"ts":1234567891}"#.as_slice(),
134        br#"{"id":"bad","value":,"ts":123}"#.as_slice(), // Invalid
135    ];
136
137    let config = ParserConfig::strict();
138    for (i, reading) in sensor_readings.iter().enumerate() {
139        let mut source = BufferSource::new(*reading);
140        match validate_json(&mut source, &config) {
141            Ok(_) => println!("   ✓ Reading {} is valid", i + 1),
142            Err(e) => println!("   ✗ Reading {} invalid: {}", i + 1, e),
143        }
144    }
145
146    println!("\n=== Validation complete ===");
147}
More examples
Hide additional examples
examples/json_parser_config.rs (line 42)
7fn main() {
8    println!("=== JSON Parser Configuration Examples ===\n");
9
10    // Example 1: Default configuration (embedded-friendly)
11    println!("1. Default Configuration (embedded-friendly):");
12    let config = ParserConfig::new();
13    println!("   Max depth: {:?}", config.max_depth);
14    println!("   Max string length: {:?}", config.max_string_length);
15    println!("   Max array size: {:?}", config.max_array_size);
16    println!("   Max object size: {:?}", config.max_object_size);
17
18    let json = r#"{"name":"sensor","values":[1,2,3,4,5]}"#;
19    let mut source = BufferSource::new(json.as_bytes());
20    match parse_with_config(&mut source, &config) {
21        Ok(node) => println!("   ✓ Parsed successfully: {:?}\n", node),
22        Err(e) => println!("   ✗ Parse error: {}\n", e),
23    }
24
25    // Example 2: Strict configuration (highly constrained)
26    println!("2. Strict Configuration (ultra-low memory):");
27    let config = ParserConfig::strict();
28    println!("   Max depth: {:?}", config.max_depth);
29    println!("   Max string length: {:?}", config.max_string_length);
30    println!("   Max array size: {:?}", config.max_array_size);
31    println!("   Max object size: {:?}", config.max_object_size);
32
33    let json = r#"{"sensor":"temp","value":23.5}"#;
34    let mut source = BufferSource::new(json.as_bytes());
35    match parse_with_config(&mut source, &config) {
36        Ok(_node) => println!("   ✓ Parsed successfully\n"),
37        Err(e) => println!("   ✗ Parse error: {}\n", e),
38    }
39
40    // Example 3: Depth limit exceeded
41    println!("3. Demonstrating Depth Limit:");
42    let config = ParserConfig::new().with_max_depth(Some(3));
43    let deeply_nested = r#"{"a":{"b":{"c":{"d":1}}}}"#;
44    let mut source = BufferSource::new(deeply_nested.as_bytes());
45    match parse_with_config(&mut source, &config) {
46        Ok(_) => println!("   ✓ Parsed (unexpected)"),
47        Err(e) => println!("   ✗ Expected error: {}\n", e),
48    }
49
50    // Example 4: String length limit
51    println!("4. Demonstrating String Length Limit:");
52    let config = ParserConfig::new().with_max_string_length(Some(10));
53    let long_string = r#"{"key":"this is a very long string that exceeds the limit"}"#;
54    let mut source = BufferSource::new(long_string.as_bytes());
55    match parse_with_config(&mut source, &config) {
56        Ok(_) => println!("   ✓ Parsed (unexpected)"),
57        Err(e) => println!("   ✗ Expected error: {}\n", e),
58    }
59
60    // Example 5: Array size limit
61    println!("5. Demonstrating Array Size Limit:");
62    let config = ParserConfig::new().with_max_array_size(Some(5));
63    let large_array = r#"[1,2,3,4,5,6,7,8,9,10]"#;
64    let mut source = BufferSource::new(large_array.as_bytes());
65    match parse_with_config(&mut source, &config) {
66        Ok(_) => println!("   ✓ Parsed (unexpected)"),
67        Err(e) => println!("   ✗ Expected error: {}\n", e),
68    }
69
70    // Example 6: Object size limit
71    println!("6. Demonstrating Object Size Limit:");
72    let config = ParserConfig::new().with_max_object_size(Some(2));
73    let large_object = r#"{"a":1,"b":2,"c":3,"d":4}"#;
74    let mut source = BufferSource::new(large_object.as_bytes());
75    match parse_with_config(&mut source, &config) {
76        Ok(_) => println!("   ✓ Parsed (unexpected)"),
77        Err(e) => println!("   ✗ Expected error: {}\n", e),
78    }
79
80    // Example 7: Custom configuration for specific use case
81    println!("7. Custom Configuration (IoT sensor data):");
82    let config = ParserConfig::new()
83        .with_max_depth(Some(4)) // Sensor data rarely deeply nested
84        .with_max_string_length(Some(64)) // Short identifiers
85        .with_max_array_size(Some(100)) // Moderate sensor readings
86        .with_max_object_size(Some(20)); // Few fields per reading
87
88    let sensor_data = r#"{
89        "device": "temp_sensor_01",
90        "timestamp": 1699876543,
91        "readings": [
92            {"temp": 23.5, "humidity": 45.2},
93            {"temp": 23.7, "humidity": 45.1}
94        ]
95    }"#;
96    let mut source = BufferSource::new(sensor_data.as_bytes());
97    match parse_with_config(&mut source, &config) {
98        Ok(node) => {
99            println!("   ✓ Parsed sensor data successfully");
100
101            // Demonstrate safe access methods
102            if let Some(device) = node.get("device").and_then(|n| n.as_str()) {
103                println!("   Device: {}", device);
104            }
105
106            if let Some(readings) = node.get("readings").and_then(|n| n.as_array()) {
107                println!("   Readings count: {}", readings.len());
108
109                // Use safe array access
110                if let Some(first) = readings.first() {
111                    if let Some(temp) = first.get("temp") {
112                        println!("   First reading temperature: {:?}", temp);
113                    }
114                }
115            }
116            println!();
117        }
118        Err(e) => println!("   ✗ Parse error: {}\n", e),
119    }
120
121    // Example 8: Unlimited configuration (not recommended for embedded)
122    println!("8. Unlimited Configuration (desktop/server use):");
123    let config = ParserConfig::unlimited();
124    println!("   Max depth: {:?}", config.max_depth);
125    println!("   Max string length: {:?}", config.max_string_length);
126    println!("   WARNING: Not recommended for embedded systems!");
127    println!("   Use this only on systems with abundant memory.\n");
128
129    // Example 9: Memory usage estimation
130    println!("9. Memory Usage Estimation:");
131    println!(
132        "   Node enum size: {} bytes",
133        std::mem::size_of::<babbel_json::Node>()
134    );
135    println!("   With strict config:");
136    println!("     Max string: 256 bytes");
137    println!("     Max array: 64 × 56 bytes = 3,584 bytes");
138    println!("     Max object: 32 × 80 bytes ≈ 2,560 bytes");
139    println!("     Per level: ~6.4 KB");
140    println!("     Total (16 levels): ~102 KB");
141    println!();
142
143    println!("   With default config:");
144    println!("     Max string: 4,096 bytes");
145    println!("     Max array: 1,024 × 56 bytes = 57,344 bytes");
146    println!("     Max object: 256 × 80 bytes ≈ 20,480 bytes");
147    println!("     Per level: ~81.9 KB");
148    println!("     Total (32 levels): ~2.6 MB");
149    println!();
150
151    println!("=== Recommendations for Different Platforms ===\n");
152
153    println!("Ultra-Low Memory (<16KB RAM):");
154    println!("  ParserConfig::strict().with_max_depth(Some(8))");
155    println!();
156
157    println!("Low Memory (16-64KB RAM):");
158    println!("  ParserConfig::strict()");
159    println!();
160
161    println!("Medium Memory (64-256KB RAM):");
162    println!("  ParserConfig::new().with_max_depth(Some(16))");
163    println!();
164
165    println!("Higher Memory (>256KB RAM):");
166    println!("  ParserConfig::new() // Use defaults");
167    println!();
168}
Source

pub fn with_max_string_length(self, max_string_length: Option<usize>) -> Self

Sets the maximum string length in bytes

Examples found in repository?
examples/json_parser_config.rs (line 52)
7fn main() {
8    println!("=== JSON Parser Configuration Examples ===\n");
9
10    // Example 1: Default configuration (embedded-friendly)
11    println!("1. Default Configuration (embedded-friendly):");
12    let config = ParserConfig::new();
13    println!("   Max depth: {:?}", config.max_depth);
14    println!("   Max string length: {:?}", config.max_string_length);
15    println!("   Max array size: {:?}", config.max_array_size);
16    println!("   Max object size: {:?}", config.max_object_size);
17
18    let json = r#"{"name":"sensor","values":[1,2,3,4,5]}"#;
19    let mut source = BufferSource::new(json.as_bytes());
20    match parse_with_config(&mut source, &config) {
21        Ok(node) => println!("   ✓ Parsed successfully: {:?}\n", node),
22        Err(e) => println!("   ✗ Parse error: {}\n", e),
23    }
24
25    // Example 2: Strict configuration (highly constrained)
26    println!("2. Strict Configuration (ultra-low memory):");
27    let config = ParserConfig::strict();
28    println!("   Max depth: {:?}", config.max_depth);
29    println!("   Max string length: {:?}", config.max_string_length);
30    println!("   Max array size: {:?}", config.max_array_size);
31    println!("   Max object size: {:?}", config.max_object_size);
32
33    let json = r#"{"sensor":"temp","value":23.5}"#;
34    let mut source = BufferSource::new(json.as_bytes());
35    match parse_with_config(&mut source, &config) {
36        Ok(_node) => println!("   ✓ Parsed successfully\n"),
37        Err(e) => println!("   ✗ Parse error: {}\n", e),
38    }
39
40    // Example 3: Depth limit exceeded
41    println!("3. Demonstrating Depth Limit:");
42    let config = ParserConfig::new().with_max_depth(Some(3));
43    let deeply_nested = r#"{"a":{"b":{"c":{"d":1}}}}"#;
44    let mut source = BufferSource::new(deeply_nested.as_bytes());
45    match parse_with_config(&mut source, &config) {
46        Ok(_) => println!("   ✓ Parsed (unexpected)"),
47        Err(e) => println!("   ✗ Expected error: {}\n", e),
48    }
49
50    // Example 4: String length limit
51    println!("4. Demonstrating String Length Limit:");
52    let config = ParserConfig::new().with_max_string_length(Some(10));
53    let long_string = r#"{"key":"this is a very long string that exceeds the limit"}"#;
54    let mut source = BufferSource::new(long_string.as_bytes());
55    match parse_with_config(&mut source, &config) {
56        Ok(_) => println!("   ✓ Parsed (unexpected)"),
57        Err(e) => println!("   ✗ Expected error: {}\n", e),
58    }
59
60    // Example 5: Array size limit
61    println!("5. Demonstrating Array Size Limit:");
62    let config = ParserConfig::new().with_max_array_size(Some(5));
63    let large_array = r#"[1,2,3,4,5,6,7,8,9,10]"#;
64    let mut source = BufferSource::new(large_array.as_bytes());
65    match parse_with_config(&mut source, &config) {
66        Ok(_) => println!("   ✓ Parsed (unexpected)"),
67        Err(e) => println!("   ✗ Expected error: {}\n", e),
68    }
69
70    // Example 6: Object size limit
71    println!("6. Demonstrating Object Size Limit:");
72    let config = ParserConfig::new().with_max_object_size(Some(2));
73    let large_object = r#"{"a":1,"b":2,"c":3,"d":4}"#;
74    let mut source = BufferSource::new(large_object.as_bytes());
75    match parse_with_config(&mut source, &config) {
76        Ok(_) => println!("   ✓ Parsed (unexpected)"),
77        Err(e) => println!("   ✗ Expected error: {}\n", e),
78    }
79
80    // Example 7: Custom configuration for specific use case
81    println!("7. Custom Configuration (IoT sensor data):");
82    let config = ParserConfig::new()
83        .with_max_depth(Some(4)) // Sensor data rarely deeply nested
84        .with_max_string_length(Some(64)) // Short identifiers
85        .with_max_array_size(Some(100)) // Moderate sensor readings
86        .with_max_object_size(Some(20)); // Few fields per reading
87
88    let sensor_data = r#"{
89        "device": "temp_sensor_01",
90        "timestamp": 1699876543,
91        "readings": [
92            {"temp": 23.5, "humidity": 45.2},
93            {"temp": 23.7, "humidity": 45.1}
94        ]
95    }"#;
96    let mut source = BufferSource::new(sensor_data.as_bytes());
97    match parse_with_config(&mut source, &config) {
98        Ok(node) => {
99            println!("   ✓ Parsed sensor data successfully");
100
101            // Demonstrate safe access methods
102            if let Some(device) = node.get("device").and_then(|n| n.as_str()) {
103                println!("   Device: {}", device);
104            }
105
106            if let Some(readings) = node.get("readings").and_then(|n| n.as_array()) {
107                println!("   Readings count: {}", readings.len());
108
109                // Use safe array access
110                if let Some(first) = readings.first() {
111                    if let Some(temp) = first.get("temp") {
112                        println!("   First reading temperature: {:?}", temp);
113                    }
114                }
115            }
116            println!();
117        }
118        Err(e) => println!("   ✗ Parse error: {}\n", e),
119    }
120
121    // Example 8: Unlimited configuration (not recommended for embedded)
122    println!("8. Unlimited Configuration (desktop/server use):");
123    let config = ParserConfig::unlimited();
124    println!("   Max depth: {:?}", config.max_depth);
125    println!("   Max string length: {:?}", config.max_string_length);
126    println!("   WARNING: Not recommended for embedded systems!");
127    println!("   Use this only on systems with abundant memory.\n");
128
129    // Example 9: Memory usage estimation
130    println!("9. Memory Usage Estimation:");
131    println!(
132        "   Node enum size: {} bytes",
133        std::mem::size_of::<babbel_json::Node>()
134    );
135    println!("   With strict config:");
136    println!("     Max string: 256 bytes");
137    println!("     Max array: 64 × 56 bytes = 3,584 bytes");
138    println!("     Max object: 32 × 80 bytes ≈ 2,560 bytes");
139    println!("     Per level: ~6.4 KB");
140    println!("     Total (16 levels): ~102 KB");
141    println!();
142
143    println!("   With default config:");
144    println!("     Max string: 4,096 bytes");
145    println!("     Max array: 1,024 × 56 bytes = 57,344 bytes");
146    println!("     Max object: 256 × 80 bytes ≈ 20,480 bytes");
147    println!("     Per level: ~81.9 KB");
148    println!("     Total (32 levels): ~2.6 MB");
149    println!();
150
151    println!("=== Recommendations for Different Platforms ===\n");
152
153    println!("Ultra-Low Memory (<16KB RAM):");
154    println!("  ParserConfig::strict().with_max_depth(Some(8))");
155    println!();
156
157    println!("Low Memory (16-64KB RAM):");
158    println!("  ParserConfig::strict()");
159    println!();
160
161    println!("Medium Memory (64-256KB RAM):");
162    println!("  ParserConfig::new().with_max_depth(Some(16))");
163    println!();
164
165    println!("Higher Memory (>256KB RAM):");
166    println!("  ParserConfig::new() // Use defaults");
167    println!();
168}
Source

pub fn with_max_array_size(self, max_array_size: Option<usize>) -> Self

Sets the maximum array size

Examples found in repository?
examples/json_validation_demo.rs (line 122)
8fn main() {
9    println!("=== JSON Validation Demo ===\n");
10
11    // Example 1: Valid simple JSON
12    println!("1. Validating simple JSON:");
13    let json1 = br#"{"name": "Alice", "age": 30, "active": true}"#;
14    match validate_simple(json1) {
15        Ok(_) => println!("   ✓ Valid JSON\n"),
16        Err(e) => println!("   ✗ Invalid: {}\n", e),
17    }
18
19    // Example 2: Valid nested JSON
20    println!("2. Validating nested structure:");
21    let json2 = br#"{
22        "user": {
23            "name": "Bob",
24            "settings": {
25                "theme": "dark",
26                "notifications": true
27            }
28        },
29        "devices": ["phone", "tablet", "laptop"]
30    }"#;
31    match validate_simple(json2) {
32        Ok(_) => println!("   ✓ Valid JSON\n"),
33        Err(e) => println!("   ✗ Invalid: {}\n", e),
34    }
35
36    // Example 3: Invalid JSON - missing quote
37    println!("3. Detecting invalid JSON (missing quote):");
38    let json3 = br#"{"name: "Alice"}"#;
39    match validate_simple(json3) {
40        Ok(_) => println!("   ✓ Valid JSON\n"),
41        Err(e) => println!("   ✗ Invalid: {}\n", e),
42    }
43
44    // Example 4: Invalid JSON - trailing comma
45    println!("4. Detecting trailing comma:");
46    let json4 = br#"{"a": 1, "b": 2,}"#;
47    match validate_simple(json4) {
48        Ok(_) => println!("   ✓ Valid JSON\n"),
49        Err(e) => println!("   ✗ Invalid: {}\n", e),
50    }
51
52    // Example 5: Configuration limits - depth
53    println!("5. Checking depth limits:");
54    let deep_json = br#"{"a":{"b":{"c":{"d":{"e":1}}}}}"#;
55    let mut source = BufferSource::new(deep_json);
56    let shallow_config = ParserConfig::new().with_max_depth(Some(3));
57
58    match validate_json(&mut source, &shallow_config) {
59        Ok(_) => println!("   ✓ Within depth limit\n"),
60        Err(e) => println!("   ✗ Exceeds limit: {}\n", e),
61    }
62
63    // Example 6: Configuration limits - string length
64    println!("6. Checking string length limits:");
65    let long_string = format!(r#"{{"data": "{}"}}"#, "x".repeat(300));
66    let mut source = BufferSource::new(long_string.as_bytes());
67    let strict_config = ParserConfig::strict(); // max 256 bytes
68
69    match validate_json(&mut source, &strict_config) {
70        Ok(_) => println!("   ✓ Within string limit\n"),
71        Err(e) => println!("   ✗ Exceeds limit: {}\n", e),
72    }
73
74    // Example 7: Valid number formats
75    println!("7. Validating various number formats:");
76    let numbers: Vec<(&[u8], &str)> = vec![
77        (b"123", "integer"),
78        (b"-456", "negative"),
79        (b"3.14", "decimal"),
80        (b"1e10", "exponential"),
81        (b"2.5e-3", "scientific"),
82    ];
83
84    for (json, desc) in numbers {
85        let mut source = BufferSource::new(json);
86        let config = ParserConfig::new();
87        match validate_json(&mut source, &config) {
88            Ok(_) => println!("   ✓ {} ({})", std::str::from_utf8(json).unwrap(), desc),
89            Err(e) => println!("   ✗ {}: {}", desc, e),
90        }
91    }
92    println!();
93
94    // Example 8: Invalid number formats
95    println!("8. Detecting invalid numbers:");
96    let invalid_numbers: Vec<(&[u8], &str)> = vec![
97        (b"01", "leading zero"),
98        (b"-.5", "no digit before decimal"),
99        (b"1.", "no digit after decimal"),
100    ];
101
102    for (json, desc) in invalid_numbers {
103        let mut source = BufferSource::new(json);
104        let config = ParserConfig::new();
105        match validate_json(&mut source, &config) {
106            Ok(_) => println!("   ✗ Should have failed: {}", desc),
107            Err(e) => println!("   ✓ Correctly rejected {}: {}", desc, e),
108        }
109    }
110    println!();
111
112    // Example 9: Large array validation
113    println!("9. Validating array size limits:");
114    let large_array = format!(
115        "[{}]",
116        (0..100)
117            .map(|i| i.to_string())
118            .collect::<Vec<_>>()
119            .join(",")
120    );
121    let mut source = BufferSource::new(large_array.as_bytes());
122    let small_config = ParserConfig::strict().with_max_array_size(Some(50));
123
124    match validate_json(&mut source, &small_config) {
125        Ok(_) => println!("   ✓ Within array limit\n"),
126        Err(e) => println!("   ✗ Exceeds limit: {}\n", e),
127    }
128
129    // Example 10: Embedded use case - sensor data validation
130    println!("10. Embedded use case - validating sensor data:");
131    let sensor_readings: Vec<&[u8]> = vec![
132        br#"{"id":"temp_01","value":23.5,"ts":1234567890}"#.as_slice(),
133        br#"{"id":"hum_02","value":45.2,"ts":1234567891}"#.as_slice(),
134        br#"{"id":"bad","value":,"ts":123}"#.as_slice(), // Invalid
135    ];
136
137    let config = ParserConfig::strict();
138    for (i, reading) in sensor_readings.iter().enumerate() {
139        let mut source = BufferSource::new(*reading);
140        match validate_json(&mut source, &config) {
141            Ok(_) => println!("   ✓ Reading {} is valid", i + 1),
142            Err(e) => println!("   ✗ Reading {} invalid: {}", i + 1, e),
143        }
144    }
145
146    println!("\n=== Validation complete ===");
147}
More examples
Hide additional examples
examples/json_parser_config.rs (line 62)
7fn main() {
8    println!("=== JSON Parser Configuration Examples ===\n");
9
10    // Example 1: Default configuration (embedded-friendly)
11    println!("1. Default Configuration (embedded-friendly):");
12    let config = ParserConfig::new();
13    println!("   Max depth: {:?}", config.max_depth);
14    println!("   Max string length: {:?}", config.max_string_length);
15    println!("   Max array size: {:?}", config.max_array_size);
16    println!("   Max object size: {:?}", config.max_object_size);
17
18    let json = r#"{"name":"sensor","values":[1,2,3,4,5]}"#;
19    let mut source = BufferSource::new(json.as_bytes());
20    match parse_with_config(&mut source, &config) {
21        Ok(node) => println!("   ✓ Parsed successfully: {:?}\n", node),
22        Err(e) => println!("   ✗ Parse error: {}\n", e),
23    }
24
25    // Example 2: Strict configuration (highly constrained)
26    println!("2. Strict Configuration (ultra-low memory):");
27    let config = ParserConfig::strict();
28    println!("   Max depth: {:?}", config.max_depth);
29    println!("   Max string length: {:?}", config.max_string_length);
30    println!("   Max array size: {:?}", config.max_array_size);
31    println!("   Max object size: {:?}", config.max_object_size);
32
33    let json = r#"{"sensor":"temp","value":23.5}"#;
34    let mut source = BufferSource::new(json.as_bytes());
35    match parse_with_config(&mut source, &config) {
36        Ok(_node) => println!("   ✓ Parsed successfully\n"),
37        Err(e) => println!("   ✗ Parse error: {}\n", e),
38    }
39
40    // Example 3: Depth limit exceeded
41    println!("3. Demonstrating Depth Limit:");
42    let config = ParserConfig::new().with_max_depth(Some(3));
43    let deeply_nested = r#"{"a":{"b":{"c":{"d":1}}}}"#;
44    let mut source = BufferSource::new(deeply_nested.as_bytes());
45    match parse_with_config(&mut source, &config) {
46        Ok(_) => println!("   ✓ Parsed (unexpected)"),
47        Err(e) => println!("   ✗ Expected error: {}\n", e),
48    }
49
50    // Example 4: String length limit
51    println!("4. Demonstrating String Length Limit:");
52    let config = ParserConfig::new().with_max_string_length(Some(10));
53    let long_string = r#"{"key":"this is a very long string that exceeds the limit"}"#;
54    let mut source = BufferSource::new(long_string.as_bytes());
55    match parse_with_config(&mut source, &config) {
56        Ok(_) => println!("   ✓ Parsed (unexpected)"),
57        Err(e) => println!("   ✗ Expected error: {}\n", e),
58    }
59
60    // Example 5: Array size limit
61    println!("5. Demonstrating Array Size Limit:");
62    let config = ParserConfig::new().with_max_array_size(Some(5));
63    let large_array = r#"[1,2,3,4,5,6,7,8,9,10]"#;
64    let mut source = BufferSource::new(large_array.as_bytes());
65    match parse_with_config(&mut source, &config) {
66        Ok(_) => println!("   ✓ Parsed (unexpected)"),
67        Err(e) => println!("   ✗ Expected error: {}\n", e),
68    }
69
70    // Example 6: Object size limit
71    println!("6. Demonstrating Object Size Limit:");
72    let config = ParserConfig::new().with_max_object_size(Some(2));
73    let large_object = r#"{"a":1,"b":2,"c":3,"d":4}"#;
74    let mut source = BufferSource::new(large_object.as_bytes());
75    match parse_with_config(&mut source, &config) {
76        Ok(_) => println!("   ✓ Parsed (unexpected)"),
77        Err(e) => println!("   ✗ Expected error: {}\n", e),
78    }
79
80    // Example 7: Custom configuration for specific use case
81    println!("7. Custom Configuration (IoT sensor data):");
82    let config = ParserConfig::new()
83        .with_max_depth(Some(4)) // Sensor data rarely deeply nested
84        .with_max_string_length(Some(64)) // Short identifiers
85        .with_max_array_size(Some(100)) // Moderate sensor readings
86        .with_max_object_size(Some(20)); // Few fields per reading
87
88    let sensor_data = r#"{
89        "device": "temp_sensor_01",
90        "timestamp": 1699876543,
91        "readings": [
92            {"temp": 23.5, "humidity": 45.2},
93            {"temp": 23.7, "humidity": 45.1}
94        ]
95    }"#;
96    let mut source = BufferSource::new(sensor_data.as_bytes());
97    match parse_with_config(&mut source, &config) {
98        Ok(node) => {
99            println!("   ✓ Parsed sensor data successfully");
100
101            // Demonstrate safe access methods
102            if let Some(device) = node.get("device").and_then(|n| n.as_str()) {
103                println!("   Device: {}", device);
104            }
105
106            if let Some(readings) = node.get("readings").and_then(|n| n.as_array()) {
107                println!("   Readings count: {}", readings.len());
108
109                // Use safe array access
110                if let Some(first) = readings.first() {
111                    if let Some(temp) = first.get("temp") {
112                        println!("   First reading temperature: {:?}", temp);
113                    }
114                }
115            }
116            println!();
117        }
118        Err(e) => println!("   ✗ Parse error: {}\n", e),
119    }
120
121    // Example 8: Unlimited configuration (not recommended for embedded)
122    println!("8. Unlimited Configuration (desktop/server use):");
123    let config = ParserConfig::unlimited();
124    println!("   Max depth: {:?}", config.max_depth);
125    println!("   Max string length: {:?}", config.max_string_length);
126    println!("   WARNING: Not recommended for embedded systems!");
127    println!("   Use this only on systems with abundant memory.\n");
128
129    // Example 9: Memory usage estimation
130    println!("9. Memory Usage Estimation:");
131    println!(
132        "   Node enum size: {} bytes",
133        std::mem::size_of::<babbel_json::Node>()
134    );
135    println!("   With strict config:");
136    println!("     Max string: 256 bytes");
137    println!("     Max array: 64 × 56 bytes = 3,584 bytes");
138    println!("     Max object: 32 × 80 bytes ≈ 2,560 bytes");
139    println!("     Per level: ~6.4 KB");
140    println!("     Total (16 levels): ~102 KB");
141    println!();
142
143    println!("   With default config:");
144    println!("     Max string: 4,096 bytes");
145    println!("     Max array: 1,024 × 56 bytes = 57,344 bytes");
146    println!("     Max object: 256 × 80 bytes ≈ 20,480 bytes");
147    println!("     Per level: ~81.9 KB");
148    println!("     Total (32 levels): ~2.6 MB");
149    println!();
150
151    println!("=== Recommendations for Different Platforms ===\n");
152
153    println!("Ultra-Low Memory (<16KB RAM):");
154    println!("  ParserConfig::strict().with_max_depth(Some(8))");
155    println!();
156
157    println!("Low Memory (16-64KB RAM):");
158    println!("  ParserConfig::strict()");
159    println!();
160
161    println!("Medium Memory (64-256KB RAM):");
162    println!("  ParserConfig::new().with_max_depth(Some(16))");
163    println!();
164
165    println!("Higher Memory (>256KB RAM):");
166    println!("  ParserConfig::new() // Use defaults");
167    println!();
168}
Source

pub fn with_max_object_size(self, max_object_size: Option<usize>) -> Self

Sets the maximum object size

Examples found in repository?
examples/json_parser_config.rs (line 72)
7fn main() {
8    println!("=== JSON Parser Configuration Examples ===\n");
9
10    // Example 1: Default configuration (embedded-friendly)
11    println!("1. Default Configuration (embedded-friendly):");
12    let config = ParserConfig::new();
13    println!("   Max depth: {:?}", config.max_depth);
14    println!("   Max string length: {:?}", config.max_string_length);
15    println!("   Max array size: {:?}", config.max_array_size);
16    println!("   Max object size: {:?}", config.max_object_size);
17
18    let json = r#"{"name":"sensor","values":[1,2,3,4,5]}"#;
19    let mut source = BufferSource::new(json.as_bytes());
20    match parse_with_config(&mut source, &config) {
21        Ok(node) => println!("   ✓ Parsed successfully: {:?}\n", node),
22        Err(e) => println!("   ✗ Parse error: {}\n", e),
23    }
24
25    // Example 2: Strict configuration (highly constrained)
26    println!("2. Strict Configuration (ultra-low memory):");
27    let config = ParserConfig::strict();
28    println!("   Max depth: {:?}", config.max_depth);
29    println!("   Max string length: {:?}", config.max_string_length);
30    println!("   Max array size: {:?}", config.max_array_size);
31    println!("   Max object size: {:?}", config.max_object_size);
32
33    let json = r#"{"sensor":"temp","value":23.5}"#;
34    let mut source = BufferSource::new(json.as_bytes());
35    match parse_with_config(&mut source, &config) {
36        Ok(_node) => println!("   ✓ Parsed successfully\n"),
37        Err(e) => println!("   ✗ Parse error: {}\n", e),
38    }
39
40    // Example 3: Depth limit exceeded
41    println!("3. Demonstrating Depth Limit:");
42    let config = ParserConfig::new().with_max_depth(Some(3));
43    let deeply_nested = r#"{"a":{"b":{"c":{"d":1}}}}"#;
44    let mut source = BufferSource::new(deeply_nested.as_bytes());
45    match parse_with_config(&mut source, &config) {
46        Ok(_) => println!("   ✓ Parsed (unexpected)"),
47        Err(e) => println!("   ✗ Expected error: {}\n", e),
48    }
49
50    // Example 4: String length limit
51    println!("4. Demonstrating String Length Limit:");
52    let config = ParserConfig::new().with_max_string_length(Some(10));
53    let long_string = r#"{"key":"this is a very long string that exceeds the limit"}"#;
54    let mut source = BufferSource::new(long_string.as_bytes());
55    match parse_with_config(&mut source, &config) {
56        Ok(_) => println!("   ✓ Parsed (unexpected)"),
57        Err(e) => println!("   ✗ Expected error: {}\n", e),
58    }
59
60    // Example 5: Array size limit
61    println!("5. Demonstrating Array Size Limit:");
62    let config = ParserConfig::new().with_max_array_size(Some(5));
63    let large_array = r#"[1,2,3,4,5,6,7,8,9,10]"#;
64    let mut source = BufferSource::new(large_array.as_bytes());
65    match parse_with_config(&mut source, &config) {
66        Ok(_) => println!("   ✓ Parsed (unexpected)"),
67        Err(e) => println!("   ✗ Expected error: {}\n", e),
68    }
69
70    // Example 6: Object size limit
71    println!("6. Demonstrating Object Size Limit:");
72    let config = ParserConfig::new().with_max_object_size(Some(2));
73    let large_object = r#"{"a":1,"b":2,"c":3,"d":4}"#;
74    let mut source = BufferSource::new(large_object.as_bytes());
75    match parse_with_config(&mut source, &config) {
76        Ok(_) => println!("   ✓ Parsed (unexpected)"),
77        Err(e) => println!("   ✗ Expected error: {}\n", e),
78    }
79
80    // Example 7: Custom configuration for specific use case
81    println!("7. Custom Configuration (IoT sensor data):");
82    let config = ParserConfig::new()
83        .with_max_depth(Some(4)) // Sensor data rarely deeply nested
84        .with_max_string_length(Some(64)) // Short identifiers
85        .with_max_array_size(Some(100)) // Moderate sensor readings
86        .with_max_object_size(Some(20)); // Few fields per reading
87
88    let sensor_data = r#"{
89        "device": "temp_sensor_01",
90        "timestamp": 1699876543,
91        "readings": [
92            {"temp": 23.5, "humidity": 45.2},
93            {"temp": 23.7, "humidity": 45.1}
94        ]
95    }"#;
96    let mut source = BufferSource::new(sensor_data.as_bytes());
97    match parse_with_config(&mut source, &config) {
98        Ok(node) => {
99            println!("   ✓ Parsed sensor data successfully");
100
101            // Demonstrate safe access methods
102            if let Some(device) = node.get("device").and_then(|n| n.as_str()) {
103                println!("   Device: {}", device);
104            }
105
106            if let Some(readings) = node.get("readings").and_then(|n| n.as_array()) {
107                println!("   Readings count: {}", readings.len());
108
109                // Use safe array access
110                if let Some(first) = readings.first() {
111                    if let Some(temp) = first.get("temp") {
112                        println!("   First reading temperature: {:?}", temp);
113                    }
114                }
115            }
116            println!();
117        }
118        Err(e) => println!("   ✗ Parse error: {}\n", e),
119    }
120
121    // Example 8: Unlimited configuration (not recommended for embedded)
122    println!("8. Unlimited Configuration (desktop/server use):");
123    let config = ParserConfig::unlimited();
124    println!("   Max depth: {:?}", config.max_depth);
125    println!("   Max string length: {:?}", config.max_string_length);
126    println!("   WARNING: Not recommended for embedded systems!");
127    println!("   Use this only on systems with abundant memory.\n");
128
129    // Example 9: Memory usage estimation
130    println!("9. Memory Usage Estimation:");
131    println!(
132        "   Node enum size: {} bytes",
133        std::mem::size_of::<babbel_json::Node>()
134    );
135    println!("   With strict config:");
136    println!("     Max string: 256 bytes");
137    println!("     Max array: 64 × 56 bytes = 3,584 bytes");
138    println!("     Max object: 32 × 80 bytes ≈ 2,560 bytes");
139    println!("     Per level: ~6.4 KB");
140    println!("     Total (16 levels): ~102 KB");
141    println!();
142
143    println!("   With default config:");
144    println!("     Max string: 4,096 bytes");
145    println!("     Max array: 1,024 × 56 bytes = 57,344 bytes");
146    println!("     Max object: 256 × 80 bytes ≈ 20,480 bytes");
147    println!("     Per level: ~81.9 KB");
148    println!("     Total (32 levels): ~2.6 MB");
149    println!();
150
151    println!("=== Recommendations for Different Platforms ===\n");
152
153    println!("Ultra-Low Memory (<16KB RAM):");
154    println!("  ParserConfig::strict().with_max_depth(Some(8))");
155    println!();
156
157    println!("Low Memory (16-64KB RAM):");
158    println!("  ParserConfig::strict()");
159    println!();
160
161    println!("Medium Memory (64-256KB RAM):");
162    println!("  ParserConfig::new().with_max_depth(Some(16))");
163    println!();
164
165    println!("Higher Memory (>256KB RAM):");
166    println!("  ParserConfig::new() // Use defaults");
167    println!();
168}

Trait Implementations§

Source§

impl Clone for ParserConfig

Source§

fn clone(&self) -> Self

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Copy for ParserConfig

Source§

impl Debug for ParserConfig

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Default for ParserConfig

Source§

fn default() -> Self

Returns the “default value” for a type. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.