Skip to main content

bencode_in_memory/
bencode_in_memory.rs

1//! Example demonstrating in-memory parsing and stringification of bencode data.
2//! This shows how to work with bencode data without file I/O using convenience functions
3//! and BufferSource/BufferDestination for more control.
4
5use babbel_bencode::{
6    BufferDestination, Node, make_node, parse_borrowed, stringify, stringify_to_bytes,
7    stringify_to_string, validate_bencode,
8};
9use std::collections::HashMap;
10
11fn main() {
12    println!("=== In-Memory Bencode Operations ===\n");
13
14    // Example 1: Using convenience functions
15    demonstrate_convenience_functions();
16
17    // Example 2: Using Buffer types for more control
18    demonstrate_buffer_types();
19
20    // Example 3: Round-trip conversions
21    demonstrate_round_trips();
22
23    // Example 4: Working with byte arrays
24    demonstrate_byte_operations();
25}
26
27/// Demonstrates the convenient parse_bytes, parse_str, stringify_to_bytes, and stringify_to_string functions
28fn demonstrate_convenience_functions() {
29    println!("--- Convenience Functions (Zero-Copy Preferred) ---");
30
31    // Parse from byte slice (zero-copy)
32    let bencode_bytes = b"i42e";
33    match parse_borrowed(bencode_bytes) {
34        Ok(node) => println!("Parsed from bytes (zero-copy): {}", node),
35        Err(e) => eprintln!("Parse error: {}", e),
36    }
37
38    // Validate bencode without parsing
39    match validate_bencode(bencode_bytes) {
40        Ok(_) => println!("Validated bencode (no allocation)"),
41        Err(e) => eprintln!("Validation error: {}", e),
42    }
43
44    // Create a node and convert to string
45    let node = make_node(vec![make_node(1), make_node(2), make_node(3)]);
46    match stringify_to_string(&node) {
47        Ok(output) => println!("Stringified to string: {}", output),
48        Err(e) => eprintln!("Stringify error: {}", e),
49    }
50
51    // Convert to bytes
52    match stringify_to_bytes(&node) {
53        Ok(output) => println!("Stringified to bytes: {:?}", output),
54        Err(e) => eprintln!("Stringify error: {}", e),
55    }
56
57    println!();
58}
59
60/// Demonstrates using BufferSource and BufferDestination for more control
61fn demonstrate_buffer_types() {
62    println!("--- Buffer Types (Zero-Copy Preferred) ---");
63
64    // Create bencode data in memory
65    let bencode_data = b"d4:name4:John3:agei30e7:hobbieslll7:reading6:codingeee";
66
67    // Parse using zero-copy
68    match parse_borrowed(bencode_data) {
69        Ok(node) => {
70            println!("Parsed dictionary (zero-copy):");
71            if let Some(dict) = node.as_dictionary() {
72                for (key, value) in dict {
73                    println!("  {:?}: {:?}", key, value);
74                }
75            }
76
77            // Stringify back using BufferDestination
78            let mut destination = BufferDestination::new();
79            // Convert BorrowedNode to Node for stringification
80            let node_owned: Node = node.to_node();
81            match stringify(&node_owned, &mut destination) {
82                Ok(_) => {
83                    let output = &destination.buffer;
84                    println!("Stringified back: {:?}", output);
85                    println!("As UTF-8: {}", String::from_utf8_lossy(output));
86                }
87                Err(e) => eprintln!("Stringify error: {}", e),
88            }
89        }
90        Err(e) => eprintln!("Parse error: {}", e),
91    }
92
93    println!();
94}
95
96/// Demonstrates round-trip conversions: create -> stringify -> parse -> compare
97fn demonstrate_round_trips() {
98    println!("--- Round-Trip Conversions ---");
99
100    // Create a complex structure
101    let mut dict = HashMap::new();
102    dict.insert("title".to_string(), make_node("Bencode Example"));
103    dict.insert("year".to_string(), make_node(2024));
104    dict.insert(
105        "tags".to_string(),
106        make_node(vec![
107            make_node("rust"),
108            make_node("bencode"),
109            make_node("serialization"),
110        ]),
111    );
112
113    let original = Node::Dictionary(dict);
114    println!("Original: {}", original);
115
116    // Convert to bencode bytes
117    match stringify_to_bytes(&original) {
118        Ok(bytes) => {
119            println!("Bencode bytes: {} bytes", bytes.len());
120            println!("Bencode string: {}", String::from_utf8_lossy(&bytes));
121
122            // Parse it back
123            match parse_borrowed(&bytes) {
124                Ok(parsed) => {
125                    // Convert BorrowedNode to Node for comparison
126                    let parsed_owned: Node = parsed.to_node();
127                    println!("Parsed back: {}", parsed_owned);
128                    println!("Matches original: {}", original == parsed_owned);
129                }
130                Err(e) => eprintln!("Parse error: {}", e),
131            }
132        }
133        Err(e) => eprintln!("Stringify error: {}", e),
134    }
135
136    println!();
137}
138
139/// Demonstrates working with raw byte arrays for binary data
140fn demonstrate_byte_operations() {
141    println!("--- Byte Operations ---");
142
143    // Various bencode-encoded values
144    let examples = vec![
145        ("Integer", b"i-123e" as &[u8]),
146        ("String", b"11:hello world"),
147        ("Empty list", b"le"),
148        ("List with items", b"li1ei2ei3ee"),
149        ("Empty dict", b"de"),
150        ("Simple dict", b"d3:key5:valuee"),
151    ];
152
153    for (description, bytes) in examples {
154        print!("{}: ", description);
155        match parse_borrowed(bytes) {
156            Ok(node) => {
157                // Convert BorrowedNode to Node for display and stringification
158                let node_owned: Node = node.to_node();
159                println!("{:?}", node_owned);
160
161                // Verify we can convert back
162                if let Ok(output) = stringify_to_bytes(&node_owned) {
163                    if output == bytes {
164                        println!("  ✓ Round-trip successful");
165                    } else {
166                        println!("  ✗ Round-trip mismatch: {:?} != {:?}", output, bytes);
167                    }
168                }
169            }
170            Err(e) => println!("Parse error: {}", e),
171        }
172    }
173
174    println!();
175}