Skip to main content

bencode_format_conversions/
bencode_format_conversions.rs

1//! Example demonstrating format conversions between bencode and various output formats.
2//! This shows how to convert bencode data to JSON, TOML, XML, YAML and back to bencode.
3
4use babbel_bencode::{
5    BufferDestination, Node, make_node, parse_str, stringify_to_string, to_json, to_toml, to_xml,
6    to_yaml,
7};
8use std::collections::HashMap;
9
10fn main() {
11    println!("=== Format Conversion Examples ===\n");
12
13    // Example 1: Simple conversions
14    demonstrate_simple_conversions();
15
16    // Example 2: Complex structure conversions
17    demonstrate_complex_conversions();
18
19    // Example 3: Round-trip conversions
20    demonstrate_round_trips();
21
22    // Example 4: Format comparison
23    demonstrate_format_comparison();
24
25    // Example 5: Practical use case - torrent metadata
26    demonstrate_torrent_conversion();
27}
28
29/// Demonstrates converting simple values to different formats
30fn demonstrate_simple_conversions() {
31    println!("--- Simple Conversions ---");
32
33    // Integer
34    let integer = Node::Integer(42);
35    print_all_formats("Integer (42)", &integer);
36
37    // String
38    let string = Node::Str("hello world".to_string());
39    print_all_formats("String ('hello world')", &string);
40
41    // Simple list
42    let list = make_node(vec![make_node(1), make_node(2), make_node(3)]);
43    print_all_formats("List [1, 2, 3]", &list);
44
45    // Simple dictionary
46    let mut dict = HashMap::new();
47    dict.insert("name".to_string(), make_node("Alice"));
48    dict.insert("age".to_string(), make_node(30));
49    let dictionary = Node::Dictionary(dict);
50    print_all_formats("Dictionary {name: 'Alice', age: 30}", &dictionary);
51
52    println!();
53}
54
55/// Helper function to print a node in all supported formats
56fn print_all_formats(description: &str, node: &Node) {
57    println!("\n{}:", description);
58
59    // Bencode (default)
60    if let Ok(bencode) = stringify_to_string(node) {
61        println!("  Bencode: {}", bencode);
62    }
63
64    // JSON
65    let mut json_dest = BufferDestination::new();
66    let _ = to_json(node, &mut json_dest).expect("Failed to convert to JSON");
67    println!("  JSON:    {}", String::from_utf8_lossy(&json_dest.buffer));
68
69    // TOML
70    let mut toml_dest = BufferDestination::new();
71    let _ = to_toml(node, &mut toml_dest).expect("Failed to convert to TOML");
72    println!("  TOML:    {}", String::from_utf8_lossy(&toml_dest.buffer));
73
74    // XML
75    let mut xml_dest = BufferDestination::new();
76    let _ = to_xml(node, &mut xml_dest).expect("Failed to convert to XML");
77    let xml_output = String::from_utf8_lossy(&xml_dest.buffer);
78    // Compact display for readability
79    let xml_compact = xml_output.replace('\n', "").replace("  ", "");
80    println!("  XML:     {}", xml_compact);
81
82    // YAML
83    let mut yaml_dest = BufferDestination::new();
84    let _ = to_yaml(node, &mut yaml_dest).expect("Failed to convert to YAML");
85    let yaml_output = String::from_utf8_lossy(&yaml_dest.buffer);
86    // Show first line only for compact display
87    let yaml_first_line = yaml_output.lines().next().unwrap_or("");
88    println!("  YAML:    {}", yaml_first_line);
89}
90
91/// Demonstrates converting complex nested structures
92fn demonstrate_complex_conversions() {
93    println!("--- Complex Structure Conversions ---");
94
95    // Build a complex nested structure
96    let mut person = HashMap::new();
97    person.insert("name".to_string(), make_node("Bob Smith"));
98    person.insert("age".to_string(), make_node(35));
99    person.insert("active".to_string(), make_node(1));
100
101    let hobbies = make_node(vec![
102        make_node("reading"),
103        make_node("coding"),
104        make_node("hiking"),
105    ]);
106    person.insert("hobbies".to_string(), hobbies);
107
108    let mut address = HashMap::new();
109    address.insert("street".to_string(), make_node("123 Main St"));
110    address.insert("city".to_string(), make_node("Anytown"));
111    address.insert("zip".to_string(), make_node("12345"));
112    person.insert("address".to_string(), Node::Dictionary(address));
113
114    let complex = Node::Dictionary(person);
115
116    println!("\nComplex structure:");
117    println!("{:#?}", complex);
118
119    println!("\n=== JSON Format ===");
120    let mut json_dest = BufferDestination::new();
121    let _ = to_json(&complex, &mut json_dest).expect("Failed to convert to JSON");
122    println!("{}", String::from_utf8_lossy(&json_dest.buffer));
123
124    println!("=== TOML Format ===");
125    let mut toml_dest = BufferDestination::new();
126    let _ = to_toml(&complex, &mut toml_dest).expect("Failed to convert to TOML");
127    println!("{}", String::from_utf8_lossy(&toml_dest.buffer));
128
129    println!("=== XML Format ===");
130    let mut xml_dest = BufferDestination::new();
131    let _ = to_xml(&complex, &mut xml_dest).expect("Failed to convert to XML");
132    println!("{}", String::from_utf8_lossy(&xml_dest.buffer));
133
134    println!("=== YAML Format ===");
135    let mut yaml_dest = BufferDestination::new();
136    let _ = to_yaml(&complex, &mut yaml_dest).expect("Failed to convert to YAML");
137    println!("{}", String::from_utf8_lossy(&yaml_dest.buffer));
138}
139
140/// Demonstrates round-trip conversions through different formats
141fn demonstrate_round_trips() {
142    println!("--- Round-Trip Conversions ---");
143
144    let original = make_node(vec![
145        make_node("item1"),
146        make_node(42),
147        make_node(vec![make_node("nested"), make_node("items")]),
148    ]);
149
150    println!("Original: {}", original);
151
152    // Bencode -> Bencode
153    if let Ok(bencode_str) = stringify_to_string(&original) {
154        println!("\nBencode representation: {}", bencode_str);
155
156        match parse_str(&bencode_str) {
157            Ok(parsed) => {
158                println!("Parsed back from bencode: {}", parsed);
159                println!("Matches original: {}", original == parsed);
160            }
161            Err(e) => eprintln!("Parse error: {}", e),
162        }
163    }
164
165    // Note: JSON/TOML/XML/YAML are output-only formats in this library
166    // They cannot be parsed back into Node structures
167    println!("\nNote: This library provides conversion TO JSON/TOML/XML/YAML,");
168    println!("but does not parse FROM these formats back to Node structures.");
169    println!("Only bencode format supports bidirectional conversion.");
170}
171
172/// Demonstrates comparing output sizes across formats
173fn demonstrate_format_comparison() {
174    println!("--- Format Size Comparison ---");
175
176    let mut data = HashMap::new();
177    data.insert("tracker".to_string(), make_node("udp://example.com:6969"));
178    data.insert("length".to_string(), make_node(1048576));
179    data.insert("name".to_string(), make_node("example-file.txt"));
180    data.insert(
181        "tags".to_string(),
182        make_node(vec![make_node("media"), make_node("document")]),
183    );
184
185    let node = Node::Dictionary(data);
186
187    println!("\nSample data: {}", node);
188    println!("\nFormat size comparison:");
189
190    // Bencode
191    if let Ok(bencode) = stringify_to_string(&node) {
192        println!("  Bencode: {} bytes", bencode.len());
193    }
194
195    // JSON
196    let mut json_dest = BufferDestination::new();
197    let _ = to_json(&node, &mut json_dest).expect("Failed to convert to JSON");
198    println!("  JSON:    {} bytes", &json_dest.buffer.len());
199
200    // TOML
201    let mut toml_dest = BufferDestination::new();
202    let _ = to_toml(&node, &mut toml_dest).expect("Failed to convert to TOML");
203    println!("  TOML:    {} bytes", &toml_dest.buffer.len());
204
205    // XML
206    let mut xml_dest = BufferDestination::new();
207    let _ = to_xml(&node, &mut xml_dest).expect("Failed to convert to XML");
208    println!("  XML:     {} bytes", &xml_dest.buffer.len());
209
210    // YAML
211    let mut yaml_dest = BufferDestination::new();
212    let _ = to_yaml(&node, &mut yaml_dest).expect("Failed to convert to YAML");
213    println!("  YAML:    {} bytes", &yaml_dest.buffer.len());
214
215    println!("\nNote: Bencode is typically the most compact format.");
216    println!();
217}
218
219/// Demonstrates converting torrent metadata to various formats
220fn demonstrate_torrent_conversion() {
221    println!("--- Torrent Metadata Conversion ---");
222
223    // Build simplified torrent structure
224    let mut file_entry = HashMap::new();
225    file_entry.insert("length".to_string(), make_node(524288));
226    file_entry.insert(
227        "path".to_string(),
228        make_node(vec![make_node("docs"), make_node("readme.txt")]),
229    );
230
231    let mut info = HashMap::new();
232    info.insert("name".to_string(), make_node("example-torrent"));
233    info.insert("piece length".to_string(), make_node(262144));
234    info.insert("pieces".to_string(), make_node("dummy_hash_string"));
235    info.insert(
236        "files".to_string(),
237        make_node(vec![Node::Dictionary(file_entry)]),
238    );
239
240    let mut torrent = HashMap::new();
241    torrent.insert(
242        "announce".to_string(),
243        make_node("udp://tracker.example.com:6969/announce"),
244    );
245    torrent.insert("created by".to_string(), make_node("babbel_bencode"));
246    torrent.insert("creation date".to_string(), make_node(1699564800));
247    torrent.insert("info".to_string(), Node::Dictionary(info));
248
249    let torrent_node = Node::Dictionary(torrent);
250
251    println!("Torrent metadata in different formats:\n");
252
253    println!("=== Original Bencode ===");
254    if let Ok(bencode) = stringify_to_string(&torrent_node) {
255        println!("{}\n", bencode);
256    }
257
258    println!("=== As JSON (human-readable) ===");
259    let mut json_dest = BufferDestination::new();
260    let _ = to_json(&torrent_node, &mut json_dest).expect("Failed to convert to JSON");
261    println!("{}\n", String::from_utf8_lossy(&json_dest.buffer));
262
263    println!("=== As YAML (human-readable) ===");
264    let mut yaml_dest = BufferDestination::new();
265    let _ = to_yaml(&torrent_node, &mut yaml_dest).expect("Failed to convert to YAML");
266    println!("{}", String::from_utf8_lossy(&yaml_dest.buffer));
267
268    println!("These conversions are useful for:");
269    println!("  - Debugging torrent files");
270    println!("  - Generating human-readable metadata reports");
271    println!("  - Converting to formats for web APIs");
272    println!("  - Data analysis and inspection");
273}