Skip to main content

bencode_error_handling/
bencode_error_handling.rs

1//! Example demonstrating proper error handling when working with bencode data.
2//! This shows how to handle parsing errors, invalid data, I/O errors, and
3//! how to write robust code that gracefully handles failures.
4
5use babbel_bencode::{FileSource, Node, make_node, parse, parse_bytes, parse_str};
6
7fn main() {
8    println!("=== Error Handling Examples ===\n");
9
10    // Example 1: Parsing invalid bencode data
11    demonstrate_parse_errors();
12
13    // Example 2: Handling file I/O errors
14    demonstrate_file_errors();
15
16    // Example 3: Type mismatch errors
17    demonstrate_type_errors();
18
19    // Example 4: Robust parsing with validation
20    demonstrate_validation();
21
22    // Example 5: Error recovery strategies
23    demonstrate_recovery();
24}
25
26/// Demonstrates various parsing error scenarios
27fn demonstrate_parse_errors() {
28    println!("--- Parse Error Handling ---");
29
30    // Test cases with invalid bencode data
31    let invalid_cases = vec![
32        ("Incomplete integer", b"i42" as &[u8]),
33        ("Invalid integer format", b"i12a34e"),
34        ("Negative zero", b"i-0e"),
35        ("String length mismatch", b"10:short"),
36        ("Missing string", b"5:"),
37        ("Incomplete list", b"li1ei2e"),
38        ("Incomplete dictionary", b"d3:key5:value"),
39        ("Invalid dictionary key", b"di1e5:valuee"),
40        ("Empty input", b""),
41        ("Garbage data", b"xyz123"),
42        ("Leading zero in integer", b"i01e"),
43        ("Leading zero in string length", b"05:hello"),
44    ];
45
46    for (description, data) in invalid_cases {
47        print!("{}: ", description);
48        match parse_bytes(data) {
49            Ok(node) => println!("Unexpectedly succeeded: {}", node),
50            Err(e) => println!("Error (as expected): {}", e),
51        }
52    }
53
54    // Demonstrate error handling with match
55    let result = parse_str("i42");
56    match result {
57        Ok(node) => println!("\nParsed successfully: {}", node),
58        Err(e) => println!("\nParse failed: {}", e),
59    }
60
61    // Demonstrate error handling with if-let
62    if let Err(e) = parse_bytes(b"invalid") {
63        println!("Caught error with if-let: {}", e);
64    }
65
66    println!();
67}
68
69/// Demonstrates handling file I/O errors
70fn demonstrate_file_errors() {
71    println!("--- File I/O Error Handling ---");
72
73    // Try to open non-existent file
74    let nonexistent_path = "nonexistent_file.bencode";
75    match FileSource::new(nonexistent_path) {
76        Ok(mut source) => {
77            println!("File opened successfully");
78            match parse(&mut source) {
79                Ok(node) => println!("Parsed: {}", node),
80                Err(e) => println!("Parse error: {}", e),
81            }
82        }
83        Err(e) => println!("Failed to open '{}': {}", nonexistent_path, e),
84    }
85
86    // Try to open invalid path
87    let invalid_path = "";
88    match FileSource::new(invalid_path) {
89        Ok(_) => println!("Unexpected success with empty path"),
90        Err(e) => println!("Failed to open empty path: {}", e),
91    }
92
93    // Demonstrate safe file reading with proper error propagation
94    match safe_read_file("example.bencode") {
95        Ok(node) => println!("Successfully read file: {}", node),
96        Err(e) => println!("Failed to read file: {}", e),
97    }
98
99    println!();
100}
101
102/// Helper function demonstrating proper error propagation
103fn safe_read_file(path: &str) -> Result<Node, String> {
104    let mut source =
105        FileSource::new(path).map_err(|e| format!("Cannot open file '{}': {}", path, e))?;
106
107    let node = parse(&mut source).map_err(|e| format!("Cannot parse file '{}': {}", path, e))?;
108
109    Ok(node)
110}
111
112/// Demonstrates handling type mismatch errors
113fn demonstrate_type_errors() {
114    println!("--- Type Mismatch Handling ---");
115
116    let data = make_node(vec![
117        make_node(42),
118        make_node("text"),
119        make_node(vec![make_node(1), make_node(2)]),
120    ]);
121
122    println!("Working with: {}", data);
123
124    // Safe type checking before access
125    if data.is_list() {
126        println!("✓ Data is a list");
127
128        if let Some(items) = data.as_list() {
129            for (i, item) in items.iter().enumerate() {
130                print!("Item {}: ", i);
131
132                // Check type before unwrapping
133                if item.is_integer() {
134                    if let Some(val) = item.as_integer() {
135                        println!("integer value = {}", val);
136                    }
137                } else if item.is_string() {
138                    if let Some(val) = item.as_string() {
139                        println!("string value = '{}'", val);
140                    }
141                } else if item.is_list() {
142                    println!("nested list with {} items", item.len());
143                } else {
144                    println!("unknown type: {}", item.type_name());
145                }
146            }
147        }
148    } else {
149        println!("✗ Data is not a list, it's a {}", data.type_name());
150    }
151
152    // Demonstrate unsafe access (returns None)
153    let integer_node = Node::Integer(42);
154    match integer_node.as_string() {
155        Some(s) => println!("Got string: {}", s),
156        None => println!("Cannot access integer as string (type mismatch)"),
157    }
158
159    println!();
160}
161
162/// Demonstrates validation of parsed data
163fn demonstrate_validation() {
164    println!("--- Data Validation ---");
165
166    // Simulate parsing torrent metadata
167    let bencode_data = b"d8:announce35:udp://tracker.example.com:6969/announce4:infod4:name12:example-file12:piece lengthi262144e6:pieces16:dummy_hash_valueee";
168
169    match parse_bytes(bencode_data) {
170        Ok(node) => match validate_torrent_metadata(&node) {
171            Ok(_) => println!("✓ Torrent metadata is valid"),
172            Err(e) => println!("✗ Validation failed: {}", e),
173        },
174        Err(e) => println!("✗ Parse failed: {}", e),
175    }
176
177    // Test with invalid structure
178    let invalid_data = make_node(vec![make_node(1), make_node(2)]);
179    match validate_torrent_metadata(&invalid_data) {
180        Ok(_) => println!("✓ Validation passed"),
181        Err(e) => println!("✗ Validation failed (expected): {}", e),
182    }
183
184    println!();
185}
186
187/// Helper function to validate torrent metadata structure
188fn validate_torrent_metadata(node: &Node) -> Result<(), String> {
189    // Check if it's a dictionary
190    let dict = node.as_dictionary().ok_or("Root must be a dictionary")?;
191
192    // Check required fields
193    dict.get("announce")
194        .ok_or("Missing 'announce' field")?
195        .as_string()
196        .ok_or("'announce' must be a string")?;
197
198    let info = dict
199        .get("info")
200        .ok_or("Missing 'info' field")?
201        .as_dictionary()
202        .ok_or("'info' must be a dictionary")?;
203
204    info.get("name")
205        .ok_or("Missing 'info.name' field")?
206        .as_string()
207        .ok_or("'info.name' must be a string")?;
208
209    info.get("piece length")
210        .ok_or("Missing 'info.piece length' field")?
211        .as_integer()
212        .ok_or("'info.piece length' must be an integer")?;
213
214    info.get("pieces")
215        .ok_or("Missing 'info.pieces' field")?
216        .as_string()
217        .ok_or("'info.pieces' must be a string")?;
218
219    Ok(())
220}
221
222/// Demonstrates error recovery strategies
223fn demonstrate_recovery() {
224    println!("--- Error Recovery Strategies ---");
225
226    // Strategy 1: Provide default values
227    let data = parse_str("i42e").unwrap_or_else(|_| {
228        println!("Parse failed, using default");
229        make_node(0)
230    });
231    println!("With fallback: {}", data);
232
233    // Strategy 2: Skip invalid items in a collection
234    let mixed_data = vec![
235        ("valid1", "i100e"),
236        ("invalid", "i42"),
237        ("valid2", "5:hello"),
238        ("invalid2", "xyz"),
239    ];
240
241    println!("\nProcessing mixed data with error recovery:");
242    let mut valid_items = Vec::new();
243    for (name, bencode) in mixed_data {
244        match parse_str(bencode) {
245            Ok(node) => {
246                println!("  ✓ {}: {}", name, node);
247                valid_items.push(node);
248            }
249            Err(e) => {
250                println!("  ✗ {}: {} (skipping)", name, e);
251            }
252        }
253    }
254    println!("Successfully parsed {} out of 4 items", valid_items.len());
255
256    // Strategy 3: Partial parsing with detailed error context
257    println!("\nPartial parsing with context:");
258    let complex_data = "d3:key5:value3:badi42ee";
259    match parse_str(complex_data) {
260        Ok(node) => {
261            println!("Parsed: {}", node);
262            // Even if parsing succeeded, validate the content
263            if let Some(dict) = node.as_dictionary() {
264                for (key, value) in dict {
265                    if value.is_none() {
266                        println!("  Warning: key '{}' has None value", key);
267                    }
268                }
269            }
270        }
271        Err(e) => {
272            println!("Parse error: {}", e);
273            println!("Input was: {}", complex_data);
274            println!("Attempting partial recovery not possible for this input");
275        }
276    }
277
278    println!();
279}