#serialization #bencode #bittorrent #serde #torrent

no-std bt_bencode

A Bencode encoding/decoding implementation

10 releases (breaking)

0.8.0 Jan 1, 2024
0.7.0 Jul 31, 2022
0.6.1 Apr 1, 2022
0.6.0 Mar 21, 2022
0.2.0 Feb 20, 2020

#222 in Encoding

Download history 146/week @ 2023-12-22 571/week @ 2023-12-29 203/week @ 2024-01-05 157/week @ 2024-01-12 67/week @ 2024-01-19 76/week @ 2024-01-26 171/week @ 2024-02-02 33/week @ 2024-02-09 147/week @ 2024-02-16 87/week @ 2024-02-23 102/week @ 2024-03-01 82/week @ 2024-03-08 52/week @ 2024-03-15 125/week @ 2024-03-22 59/week @ 2024-03-29 80/week @ 2024-04-05

320 downloads per month
Used in 4 crates

MIT/Apache

155KB
4K SLoC

BtBencode

BtBencode is a library which can help with Bencode encoding/decoding. Bencode is primarily used in BitTorrent related applications.

It uses the Serde library to serialize and deserialize Bencode data. It is similar to Serde JSON in terms of functionality and implementation.

Examples

An example serializing a standard Rust collection type and then deserializing into a custom type:

use std::collections::BTreeMap;
use serde_derive::Deserialize;

let mut dict: BTreeMap<String, String> = BTreeMap::new();
dict.insert(String::from("url"), String::from("https://example.com/"));

let serialized_bytes = bt_bencode::to_vec(&dict)?;

#[derive(Deserialize)]
struct Info<'a> {
    url: &'a str,
}

let info: Info = bt_bencode::from_slice(&serialized_bytes)?;
assert_eq!(info.url, "https://example.com/");

An example deserializing from a slice of bytes into a general Value representation and then from the Value instance into a more strongly typed data structure.

use serde_derive::{Serialize, Deserialize};

use bt_bencode::Value;

#[derive(Serialize, Deserialize)]
struct Info {
    t: String,
    url: String,
}

let serialized_bytes = bt_bencode::to_vec(&Info {
    t: String::from("query"),
    url: String::from("https://example.com/"),
})?;

let value: Value = bt_bencode::from_slice(&serialized_bytes)?;
assert_eq!(value["t"].as_str().unwrap(), "query");
assert_eq!(
    value.get("url").and_then(|url| url.as_str()).unwrap(),
    "https://example.com/"
);

let info: Info = bt_bencode::from_value(value)?;
assert_eq!(info.t, "query");
assert_eq!(info.url, "https://example.com/");

Installation

cargo add bt_bencode

By default, the std feature is enabled.

Alloc only

If the host environment has an allocator but does not have access to the Rust std library:

cargo add --no-default-features --features alloc bt_bencode

License

Licensed under either of Apache License, Version 2.0 or MIT License at your option.

Contributions

Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the work by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions.

Dependencies

~115–360KB