### Use Low-Level Bencode Serializer Source: https://context7.com/toby/serde-bencode/llms.txt Demonstrates direct usage of the Serializer type for custom serialization workflows. Shows how to create a serializer, serialize data, and extract the resulting bytes. Includes examples of both consuming and non-consuming access to serialized data. ```rust use serde::Serialize; use serde_bencode::Serializer; fn main() -> Result<(), Box> { let data = vec!["foo", "bar", "baz"]; // Create serializer let mut serializer = Serializer::new(); // Serialize data data.serialize(&mut serializer)?; // Extract bytes let bytes = serializer.into_vec(); // Result: l3:foo3:bar3:baze println!("Result: {}", String::from_utf8_lossy(&bytes)); // Alternative: use as_ref() to peek without consuming let mut serializer2 = Serializer::new(); vec![1, 2, 3].serialize(&mut serializer2)?; let preview: &[u8] = serializer2.as_ref(); println!("Preview: {}", String::from_utf8_lossy(preview)); Ok(()) } ``` -------------------------------- ### Parse BitTorrent .torrent files with Bencode Source: https://context7.com/toby/serde-bencode/llms.txt Example of parsing .torrent file structures with proper handling of binary data and optional fields. Demonstrates complex nested structures, field renaming, and handling of optional fields. Requires serde_bytes crate for proper byte buffer handling. ```rust use serde_derive::Deserialize; use serde_bytes::ByteBuf; use std::fs; #[derive(Debug, Deserialize)] struct File { path: Vec, length: i64, #[serde(default)] md5sum: Option, } #[derive(Debug, Deserialize)] struct Info { pub name: String, pub pieces: ByteBuf, // SHA1 hashes #[serde(rename = "piece length")] pub piece_length: i64, #[serde(default)] pub length: Option, #[serde(default)] pub files: Option>, } #[derive(Debug, Deserialize)] struct Torrent { info: Info, #[serde(default)] announce: Option, #[serde(default)] #[serde(rename = "creation date")] creation_date: Option, #[serde(default)] comment: Option, } fn main() -> Result<(), Box> { let data = fs::read("example.torrent")?; let torrent: Torrent = serde_bencode::from_bytes(&data)?; println!("Name: {}", torrent.info.name); println!("Announce: {:?}", torrent.announce); println!("Piece length: {}", torrent.info.piece_length); println!("Creation date: {:?}", torrent.creation_date); if let Some(files) = &torrent.info.files { for file in files { println!("File: {:?} ({} bytes)", file.path, file.length); } } Ok(()) } ``` -------------------------------- ### Serialize Rust data structures to Bencode bytes Source: https://context7.com/toby/serde-bencode/llms.txt Shows how to convert Rust data structures to raw Bencode byte vectors for binary operations. Useful for network protocols or file formats requiring binary Bencode data. The example serializes a configuration struct to bytes and prints the result. ```rust use serde_derive::Serialize; #[derive(Serialize)] struct Config { port: i64, host: String, enabled: bool, } fn main() -> Result<(), Box> { let config = Config { port: 8080, host: "localhost".to_string(), enabled: true, }; // Serialize to bytes let bytes = serde_bencode::to_bytes(&config)?; // Result: d7:enabledi1e4:host9:localhost4:porti8080ee println!("Encoded: {}", String::from_utf8_lossy(&bytes)); Ok(()) } ``` -------------------------------- ### Handle Optional Fields with Defaults in Rust Source: https://context7.com/toby/serde-bencode/llms.txt This example demonstrates handling optional fields and defaults in Bencode deserialization using serde attributes. It defines a Config struct with required and optional fields, deserializes from a minimal Bencode string, and serializes back with skipped empty fields. Dependencies include serde_derive. Inputs are Bencode dictionaries, outputs are Config structs. It uses serde's default attribute and skip_serializing_if for customization, limiting to i64 and Vec types without custom error handling for invalid defaults. ```rust use serde_derive::{Serialize, Deserialize}; #[derive(Serialize, Deserialize, Debug)] struct Config { // Required field version: i64, // Optional with explicit None default #[serde(default)] timeout: Option, // Optional with custom default #[serde(default = "default_port")] port: i64, // Skip serialization if empty #[serde(skip_serializing_if = "Vec::is_empty")] #[serde(default)] tags: Vec, } fn default_port() -> i64 { 8080 } fn main() -> Result<(), Box> { // Minimal input missing optional fields let data = "d7:versioni2ee"; let config: Config = serde_bencode::from_str(data)?; assert_eq!(config.version, 2); assert_eq!(config.timeout, None); assert_eq!(config.port, 8080); // Uses default assert_eq!(config.tags.len(), 0); // Serialize (tags are skipped because empty) let encoded = serde_bencode::to_string(&config)?; assert!(!encoded.contains("tags")); Ok(()) } ``` -------------------------------- ### Deserialize Bencode bytes to Rust structures Source: https://context7.com/toby/serde-bencode/llms.txt Demonstrates parsing of raw Bencode byte data into typed Rust structures. Useful for processing binary Bencode formats like torrent files. The example parses a message structure from byte array and validates the parsed values. ```rust use serde_derive::Deserialize; #[derive(Deserialize, Debug)] struct Message { id: i64, text: String, } fn main() -> Result<(), Box> { // Raw bencode bytes: d2:idi42e4:text11:Hello Worlde let data = b"d2:idi42e4:text11:Hello Worlde"; let message: Message = serde_bencode::from_bytes(data)?; assert_eq!(message.id, 42); assert_eq!(message.text, "Hello World"); Ok(()) } ``` -------------------------------- ### Deserialize Generic Value Types in Rust Source: https://context7.com/toby/serde-bencode/llms.txt This example uses the Value enum for dynamic Bencode data when the structure is unknown at compile time. It parses a Bencode string, performs pattern matching on types like Dict, Int, Bytes, and List, creates Value objects from primitives, and serializes them back. Dependencies include serde_bencode and std::collections::HashMap. Inputs are Bencode-encoded strings, outputs are parsed Value instances or serialized strings. It assumes UTF-8 encoded bytes for string data and does not handle errors beyond basic Result propagation. ```rust use serde_bencode::value::Value; use std::collections::HashMap; fn main() -> Result<(), Box> { // Parse unknown structure let data = "d3:agei25e4:name3:Bob4:tagsli1ei2ei3eee"; let parsed: Value = serde_bencode::from_str(data)?; // Pattern match on value types if let Value::Dict(map) = &parsed { if let Some(Value::Int(age)) = map.get(b"age" as &[u8]) { println!("Age: {}", age); } if let Some(Value::Bytes(name)) = map.get(b"name" as &[u8]) { println!("Name: {}", String::from_utf8_lossy(name)); } if let Some(Value::List(tags)) = map.get(b"tags" as &[u8]) { println!("Tags: {:?}", tags); } } // Create Value from primitives let int_val: Value = 42i64.into(); let str_val: Value = "hello".into(); let list_val: Value = vec![ Value::Int(1), Value::Int(2), Value::Int(3), ].into(); // Serialize back let encoded = serde_bencode::to_string(&list_val)?; assert_eq!(encoded, "li1ei2ei3ee"); Ok(()) } ``` -------------------------------- ### Run Benchmarks with Cargo Source: https://github.com/toby/serde-bencode/blob/master/README.md This command executes the benchmarking suite for the serde_bencode project using Cargo's built-in bench command. It runs performance tests to measure encoding/decoding speed. The command should be executed in the project root directory where Cargo.toml is located. ```console cargo bench ``` -------------------------------- ### Parse Bencode Byte Strings (Rust) Source: https://context7.com/toby/serde-bencode/llms.txt Shows how to parse Bencode byte strings. The input is a string representing a Bencode byte string with a length prefix, and the output is the corresponding String. It uses serde_bencode::from_str function. ```Rust let str_data = "5:hello"; let str_val: String = serde_bencode::from_str(str_data)?; assert_eq!(str_val, "hello") ``` -------------------------------- ### Configure Cargo Dependencies for serde_bencode Source: https://github.com/toby/serde-bencode/blob/master/README.md This snippet shows how to add serde_bencode and its required dependencies (serde and serde_derive) to a Rust project's Cargo.toml file. It specifies version constraints compatible with the library. This configuration enables serialization and deserialization of bencode data structures. ```toml [dependencies] serde_bencode = "^0.2.4" serde = "^1.0.0" serde_derive = "^1.0.0" ``` -------------------------------- ### Parse Bencode Lists (Rust) Source: https://context7.com/toby/serde-bencode/llms.txt Demonstrates parsing Bencode lists. The input is a string representing a Bencode list containing integers, and the output is a Vec. It uses serde_bencode::from_str function. ```Rust let list_data = "li1ei2ei3ee"; let list_val: Vec = serde_bencode::from_str(list_data)?; assert_eq!(list_val, vec![1, 2, 3]); ``` -------------------------------- ### Serialize and deserialize Rust structs to Bencode Source: https://context7.com/toby/serde-bencode/llms.txt Demonstrates basic serialization and deserialization of Rust structs to/from Bencode format using Serde derive macros. Shows automatic conversion between Rust data structures and Bencode strings. Requires serde_derive crate for Serialize and Deserialize traits. ```rust use serde_derive::{Serialize, Deserialize}; #[derive(Serialize, Deserialize, PartialEq, Eq, Debug)] struct Product { name: String, price: u32, } fn main() -> Result<(), Box> { let apple = Product { name: "Apple".to_string(), price: 130, }; // Serialize to Bencode string let serialized = serde_bencode::to_string(&apple)?; assert_eq!(serialized, "d4:name5:Apple5:pricei130ee"); // Deserialize back to struct let deserialized: Product = serde_bencode::from_str(&serialized)?; assert_eq!(deserialized, apple); Ok(()) } ``` -------------------------------- ### Serialize Binary Data with serde_bytes Source: https://context7.com/toby/serde-bencode/llms.txt Shows how to efficiently handle raw binary data using serde_bytes for non-UTF8 byte sequences. Demonstrates serialization and deserialization of structures containing binary data using both Vec and ByteBuf types. ```rust use serde_derive::{Serialize, Deserialize}; use serde_bytes::{ByteBuf, Bytes}; #[derive(Serialize, Deserialize, Debug)] struct BinaryData { name: String, // Efficient serialization of byte arrays #[serde(with = "serde_bytes")] signature: Vec, // For owned byte data hash: ByteBuf, } fn main() -> Result<(), Box> { let data = BinaryData { name: "document.pdf".to_string(), signature: vec![0xDE, 0xAD, 0xBE, 0xEF], hash: ByteBuf::from(vec![0x01, 0x23, 0x45, 0x67, 0x89, 0xAB]), }; // Serialize (bytes are encoded as bencode byte strings) let encoded = serde_bencode::to_bytes(&data)?; // Deserialize let decoded: BinaryData = serde_bencode::from_bytes(&encoded)?; assert_eq!(decoded.name, "document.pdf"); assert_eq!(decoded.signature, vec![0xDE, 0xAD, 0xBE, 0xEF]); Ok(()) } ``` -------------------------------- ### Parse Bencode Integers (Rust) Source: https://context7.com/toby/serde-bencode/llms.txt Demonstrates parsing Bencode integers (positive and negative) using the serde-bencode library. It expects valid Bencode integer strings as input and outputs the parsed i64 value. It utilizes serde_bencode::from_str function. ```Rust let int_data = "i42e"; let int_val: i64 = serde_bencode::from_str(int_data)?; assert_eq!(int_val, 42); // Negative integers let neg_data = "i-10e"; let neg_val: i64 = serde_bencode::from_str(neg_data)?; assert_eq!(neg_val, -10); ``` -------------------------------- ### Parse Bencode Dictionaries (Rust) Source: https://context7.com/toby/serde-bencode/llms.txt Shows how to parse Bencode dictionaries. The input is a string representing a Bencode dictionary with key-value pairs, and the output is a serde_bencode::value::Value. It utilizes serde_bencode::from_str function. ```Rust let dict_data = "d3:agei30e4:name5:Alicee"; let dict_val: serde_bencode::value::Value = serde_bencode::from_str(dict_data)?; println!("Parsed dict: {:?}", dict_val); ``` -------------------------------- ### Handle Bencode Deserialization Errors Source: https://context7.com/toby/serde-bencode/llms.txt Shows comprehensive error handling for different failure scenarios during bencode deserialization. Covers missing fields, invalid types, malformed data, and UTF-8 validation errors. Uses match expressions to handle specific error types. ```rust use serde_bencode::{Error, from_str}; use serde_derive::Deserialize; #[derive(Deserialize, Debug)] struct Data { required_field: String, number: i64, } fn main() { // Missing required field let result1 = from_str::("d6:numberi42ee"); match result1 { Err(Error::MissingField(field)) => { println!("Missing field: {}", field); } _ => unreachable!(), } // Invalid type let result2 = from_str::("d6:number5:hello14:required_field5:valuee"); match result2 { Err(Error::InvalidType(msg)) => { println!("Type error: {}", msg); } _ => unreachable!(), } // Malformed bencode let result3 = from_str::("d6:numberi42e"); // Missing 'e' terminator match result3 { Err(Error::EndOfStream) => { println!("Unexpected end of stream"); } _ => unreachable!(), } // Invalid UTF-8 in string field let invalid_utf8 = b"d6:numberi1e14:required_field4:\xff\xfeTXe"; let result4 = serde_bencode::from_bytes::(invalid_utf8); match result4 { Err(Error::InvalidValue(msg)) => { println!("Invalid value: {}", msg); } _ => unreachable!(), } } ``` -------------------------------- ### Serialize and Deserialize Rust Enums with Bencode Source: https://context7.com/toby/serde-bencode/llms.txt Demonstrates serialization and deserialization of Rust enums with different variants (unit, struct, tuple) using serde-bencode. Shows how to use serde attributes for renaming variants. Requires serde_derive and serde_bencode crates. ```rust use serde_derive::{Serialize, Deserialize}; #[derive(Serialize, Deserialize, Debug, PartialEq)] enum Status { #[serde(rename = "pending")] Pending, #[serde(rename = "active")] Active { since: i64 }, #[serde(rename = "error")] Error(String), } #[derive(Serialize, Deserialize, Debug, PartialEq)] struct Task { id: i64, status: Status, } fn main() -> Result<(), Box> { // Unit variant let task1 = Task { id: 1, status: Status::Pending, }; let enc1 = serde_bencode::to_string(&task1)?; let dec1: Task = serde_bencode::from_str(&enc1)?; assert_eq!(task1, dec1); // Struct variant let task2 = Task { id: 2, status: Status::Active { since: 1234567890 }, }; let enc2 = serde_bencode::to_string(&task2)?; let dec2: Task = serde_bencode::from_str(&enc2)?; assert_eq!(task2, dec2); // Tuple variant let task3 = Task { id: 3, status: Status::Error("timeout".to_string()), }; let enc3 = serde_bencode::to_string(&task3)?; let dec3: Task = serde_bencode::from_str(&enc3)?; assert_eq!(task3, dec3); Ok(()) } ``` -------------------------------- ### Parse Nested Bencode Structures (Rust) Source: https://context7.com/toby/serde-bencode/llms.txt Demonstrates parsing nested Bencode structures containing a list and a dictionary. The input is a string representing a nested Bencode structure, and the output is a serde_bencode::value::Value. It uses serde_bencode::from_str function. ```Rust let nested = "d4:listli1ei2ee4:dictd3:key5:valueee"; let nested_val: serde_bencode::value::Value = serde_bencode::from_str(nested)?; println!("Nested: {:?}", nested_val); ``` -------------------------------- ### Rename Fields in Bencode Serialization in Rust Source: https://context7.com/toby/serde-bencode/llms.txt This code shows how to map Rust field names to different Bencode keys using serde rename attributes. It defines a Metadata struct with renamed fields, serializes it to Bencode, and deserializes back. Dependencies include serde_derive. Inputs are Rust structs, outputs are Bencode strings with specified key formats. It supports custom naming conventions like kebab-case for keys, assuming all fields are serializable types and not handling key conflicts or non-string keys. ```rust use serde_derive::{Serialize, Deserialize}; #[derive(Serialize, Deserialize, Debug)] struct Metadata { #[serde(rename = "content-type")] content_type: String, #[serde(rename = "created-at")] created_at: i64, #[serde(rename = "modified-at")] modified_at: i64, // Snake case in Rust, kebab case in bencode #[serde(rename = "file-size")] file_size: i64, } fn main() -> Result<(), Box> { let meta = Metadata { content_type: "application/json".to_string(), created_at: 1234567890, modified_at: 1234567900, file_size: 2048, }; let encoded = serde_bencode::to_string(&meta)?; // Keys in bencode use renamed format assert!(encoded.contains("content-type")); assert!(encoded.contains("file-size")); let decoded: Metadata = serde_bencode::from_str(&encoded)?; assert_eq!(decoded.content_type, "application/json"); Ok(()) } ``` -------------------------------- ### Serialize Nested Structures in Rust Source: https://context7.com/toby/serde-bencode/llms.txt This code serializes and deserializes complex nested data structures like structs with vectors and HashMaps using serde-bencode. It defines a User struct, serializes it to a Bencode string (with sorted map keys), and deserializes it back. Dependencies include serde_derive and std::collections::HashMap. Inputs are Rust structs, outputs are Bencode strings. It requires the struct to implement Serialize and Deserialize traits and assumes map keys are automatically sorted during serialization. ```rust use serde_derive::{Serialize, Deserialize}; use std::collections::HashMap; #[derive(Serialize, Deserialize, Debug, PartialEq)] struct User { id: i64, username: String, roles: Vec, metadata: HashMap, } fn main() -> Result<(), Box> { let mut metadata = HashMap::new(); metadata.insert("country".to_string(), "US".to_string()); metadata.insert("timezone".to_string(), "PST".to_string()); let user = User { id: 1001, username: "alice".to_string(), roles: vec!["admin".to_string(), "moderator".to_string()], metadata, }; // Serialize (note: map keys are automatically sorted) let encoded = serde_bencode::to_string(&user)?; println!("Encoded: {}", encoded); // Deserialize let decoded: User = serde_bencode::from_str(&encoded)?; assert_eq!(user, decoded); Ok(()) } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.