pub struct BufferDestination {
pub buffer: Vec<u8>,
}Expand description
Destination implementation for writing bencode data to a memory buffer
In-memory byte buffer destination (Vec<u8>).
Fields§
§buffer: Vec<u8>Internal vector storing the raw bytes
Implementations§
Source§impl Buffer
impl Buffer
Sourcepub fn new() -> Buffer
pub fn new() -> Buffer
Creates a new buffer destination.
Examples found in repository?
examples/bencode_full.rs (line 22)
10fn main() {
11 // Parse a bencode dictionary
12 let dict = b"d3:agei25e4:name4:Johne";
13
14 if let Ok(node) = parse_bytes(dict) {
15 // Convert back to bencode
16 if let Ok(output) = stringify_to_bytes(&node) {
17 assert_eq!(output, dict);
18 println!("Bencode: {}", String::from_utf8_lossy(&output));
19 }
20
21 // All format conversions available
22 let mut buffer = BufferDestination::new();
23 if to_json(&node, &mut buffer).is_ok() {
24 println!("JSON: {}", String::from_utf8_lossy(&buffer.buffer));
25 }
26
27 let mut buffer = BufferDestination::new();
28 if to_toml(&node, &mut buffer).is_ok() {
29 println!("TOML: {}", String::from_utf8_lossy(&buffer.buffer));
30 }
31
32 let mut buffer = BufferDestination::new();
33 if to_xml(&node, &mut buffer).is_ok() {
34 println!("XML: {}", String::from_utf8_lossy(&buffer.buffer));
35 }
36
37 let mut buffer = BufferDestination::new();
38 if to_yaml(&node, &mut buffer).is_ok() {
39 println!("YAML: {}", String::from_utf8_lossy(&buffer.buffer));
40 }
41 }
42}More examples
examples/bencode_in_memory.rs (line 78)
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}examples/bencode_format_conversions.rs (line 65)
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}Sourcepub fn with_capacity(capacity: usize) -> Buffer
pub fn with_capacity(capacity: usize) -> Buffer
Creates a new buffer with initial capacity.
Sourcepub fn into_string(self) -> Result<String, FromUtf8Error>
pub fn into_string(self) -> Result<String, FromUtf8Error>
Converts the buffer content into an owned String without reallocating if valid UTF-8.
Trait Implementations§
Source§impl BencodeWrite for Buffer
impl BencodeWrite for Buffer
Source§fn write_byte(&mut self, byte: u8)
fn write_byte(&mut self, byte: u8)
Writes a single byte to the destination.
Source§fn write_bytes(&mut self, bytes: &[u8])
fn write_bytes(&mut self, bytes: &[u8])
Writes multiple bytes from a raw byte slice to the destination (binary-safe).
Source§impl BufferedWrite for Buffer
impl BufferedWrite for Buffer
Source§impl IByteWriter for Buffer
impl IByteWriter for Buffer
Source§impl IClearable for Buffer
impl IClearable for Buffer
Source§impl IDestination for Buffer
impl IDestination for Buffer
Source§impl IDestination for Buffer
impl IDestination for Buffer
Auto Trait Implementations§
impl Freeze for Buffer
impl RefUnwindSafe for Buffer
impl Send for Buffer
impl Sync for Buffer
impl Unpin for Buffer
impl UnsafeUnpin for Buffer
impl UnwindSafe for Buffer
Blanket Implementations§
Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Mutably borrows from an owned value. Read more