Skip to main content

bencode_iterative/
bencode_iterative.rs

1//! Iterative (stack-based) parser example
2//!
3//! **Best Practice:** Use `parse_iterative` and related functions for deeply nested bencode data or in embedded/stack-limited environments.
4//! This avoids stack overflows by using an explicit heap stack, making parsing robust and predictable for any nesting depth.
5//!
6//! Demonstrates the iterative parser that avoids recursion, making it suitable
7//! for embedded systems with limited stack space or handling deeply nested structures.
8//!
9//! The iterative parser uses an explicit heap-allocated stack instead of the call stack,
10//! preventing stack overflow when parsing deeply nested bencode structures.
11
12use babbel_bencode::{BufferSource, parse_iterative, stringify_to_bytes};
13
14fn main() {
15    println!("=== Iterative Parser Demo ===\n");
16
17    // Example 1: Simple parsing comparison
18    println!("1. Simple structure:");
19    let simple = b"d3:agei25e4:name4:Johne";
20
21    let mut source = BufferSource::new(simple);
22    match parse_iterative(&mut source) {
23        Ok(node) => {
24            println!("   Parsed successfully with iterative parser");
25            if let Ok(output) = stringify_to_bytes(&node) {
26                println!("   Output: {}", String::from_utf8_lossy(&output));
27            }
28        }
29        Err(e) => println!("   Error: {}", e),
30    }
31
32    // Example 2: Deeply nested lists
33    println!("\n2. Deeply nested structure (100 levels):");
34    let mut deeply_nested = String::from("i42e");
35    for _ in 0..100 {
36        deeply_nested = format!("l{}e", deeply_nested);
37    }
38    println!("   Created nested list with {} bytes", deeply_nested.len());
39
40    // Try with iterative parser (should work)
41    match babbel_bencode::parse_bytes_iterative(deeply_nested.as_bytes()) {
42        Ok(_) => println!("   ✓ Iterative parser succeeded"),
43        Err(e) => println!("   ✗ Iterative parser failed: {}", e),
44    }
45
46    // Try with recursive parser (works but uses more stack)
47    match babbel_bencode::parse_bytes(deeply_nested.as_bytes()) {
48        Ok(_) => println!("   ✓ Recursive parser succeeded (but used more stack)"),
49        Err(e) => println!("   ✗ Recursive parser failed: {}", e),
50    }
51
52    // Example 3: Very deeply nested (1000 levels) - only iterative should handle well
53    println!("\n3. Very deeply nested structure (1000 levels):");
54    let mut very_deep = String::from("i1e");
55    for _ in 0..1000 {
56        very_deep = format!("l{}e", very_deep);
57    }
58    println!("   Created nested list with {} bytes", very_deep.len());
59
60    match babbel_bencode::parse_bytes_iterative(very_deep.as_bytes()) {
61        Ok(_) => println!("   ✓ Iterative parser succeeded (no stack issues)"),
62        Err(e) => println!("   ✗ Iterative parser failed: {}", e),
63    }
64
65    // Example 4: Complex nested dictionary
66    println!("\n4. Complex nested dictionary:");
67    let complex = b"d4:infod6:lengthi123e4:name9:test.file12:piece lengthi16384eee";
68
69    let mut source = BufferSource::new(complex);
70    match parse_iterative(&mut source) {
71        Ok(node) => {
72            println!("   Parsed complex structure successfully");
73            if let Ok(output) = stringify_to_bytes(&node) {
74                println!("   Size: {} bytes", output.len());
75            }
76        }
77        Err(e) => println!("   Error: {}", e),
78    }
79
80    // Example 5: Deeply nested mixed structure
81    println!("\n5. Mixed nested structure:");
82    let mixed = b"d4:dictd1:ai1e1:bi2ee4:listlli1ei2eeli3ei4eeee";
83
84    let mut source = BufferSource::new(mixed);
85    match parse_iterative(&mut source) {
86        Ok(node) => {
87            println!("   Parsed mixed nested structure");
88            if let Ok(output) = stringify_to_bytes(&node) {
89                println!("   Output: {}", String::from_utf8_lossy(&output));
90            }
91        }
92        Err(e) => println!("   Error: {}", e),
93    }
94
95    println!("\n=== Advantages of Iterative Parser ===");
96    println!("✓ No recursion - uses explicit stack on heap");
97    println!("✓ Safe for deeply nested structures (>1000 levels)");
98    println!("✓ Predictable memory usage");
99    println!("✓ Ideal for embedded systems with limited stack space");
100    println!("✓ Same functionality as recursive parser");
101}