Skip to main content

json_parser_config/
json_parser_config.rs

1//! Example demonstrating parser configuration for memory-constrained embedded systems
2//!
3//! This example shows how to use ParserConfig to control resource usage when parsing JSON.
4
5use babbel_json::{BufferSource, ParserConfig, parse_with_config};
6
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}