Please check the build logs for more information.
See Builds for ideas on how to fix a failed build, or Metadata for how to configure docs.rs builds.
If you believe this is docs.rs' fault, open an issue.
babbel_bencode
A Rust library for parsing, constructing, and converting Bencode data. Designed for embedded systems, resource-constrained environments, and general-purpose use. Supports round-tripping Bencode and conversion to JSON, YAML, XML, and TOML.
Features
- Parse Bencode into a typed tree (
Node) - Serialize
Nodeback to canonical Bencode - Convert
Nodeto JSON, YAML, XML, or TOML (optional Cargo features) - Zero-copy borrowed parsing via
BorrowedNode— no heap allocation no_stdcompatible (disable the defaultstdfeature)- Memory pool / arena allocation (
Arena,StackBuffer,MemoryTracker) - Stack-based iterative parser — safe for deeply nested structures
- Validation helpers for ergonomic field extraction (
get_required,get_int_required, …) - Configurable parsing depth (
ParserConfig) and canonicalisation enforcement (EncoderConfig) - Read/write from files or in-memory buffers
Installation
Add to your Cargo.toml:
[]
= "0.1.1"
Or as a path dependency within this workspace:
[]
= { = "crates/bencode" }
All binary-safe streaming I/O (IByteStream, FileSource, FileDestination, Buffer) is unified with and powered by babbel_core::io.
To minimise binary size, disable unused format-conversion features:
[]
= { = "0.1.1", = false, = ["std", "json"] }
Available features: std (default), json, toml, xml, yaml.
Release Builds & LTO for Optimal Size
For the smallest and fastest binaries, enable Link Time Optimization (LTO):
[]
= true
Then build with:
Quick Examples
Parse a .torrent file and convert to YAML
use ;
let mut src = new?;
let node = parse?;
let mut dst = new?;
to_yaml;
Round-trip a Bencode buffer
use ;
let raw = b"d3:foo3:bar4:spamli1ei2ei3eee";
let node = parse_bytes?;
let encoded = stringify_to_bytes;
assert_eq!;
Construct a Node and render as JSON
use ;
// Using the From trait with an array of key-value pairs
let node = from;
let mut dst = new;
to_json;
Validate and extract fields ergonomically
use parse_bytes;
let node = parse_bytes?;
let name: &str = node.get_string_required?;
let age: i64 = node.get_int_required?;
Data Model
Node::Integer(i64) — Bencode integer
Node::Str(String) — Bencode string (UTF-8)
Node::List(Vec<Node>) — Bencode list
Node::Dictionary(HashMap<String, Node>) — Bencode dictionary
Node::None — Empty / uninitialized node
Nodes implement Clone, Debug, PartialEq, and Display.
Creating Nodes
use ;
use HashMap;
// Direct variants
let i = Integer;
let s = Str;
// Via the generic helper (uses From conversions)
let n = make_node; // -> Node::Integer(99)
let n = make_node; // -> Node::Str("world")
let n = make_node; // -> Node::List([Integer(1), Integer(2)])
// Array literal short-hand
let list = from;
let dict = from;
API Overview
Parsing
| Function | Description |
|---|---|
parse(&mut src) |
Parse from any Source (file or buffer) |
parse_bytes(data: &[u8]) |
Parse directly from a byte slice |
parse_str(data: &str) |
Parse directly from a string slice |
parse_iterative(&mut src) |
Stack-based iterative parse (deep nesting safe) |
parse_bytes_iterative(data) |
Iterative parse from byte slice |
parse_str_iterative(data) |
Iterative parse from string slice |
parse_borrowed(data: &[u8]) |
Zero-copy parse returning BorrowedNode |
validate_bencode(data: &[u8]) |
Validate without building a node tree |
Stringifying
| Function | Description |
|---|---|
stringify(&node, &mut dst) |
Write canonical Bencode to any Destination |
stringify_to_bytes(&node) |
Return Bencode as Vec<u8> |
stringify_to_string(&node) |
Return Bencode as String |
to_json(&node, &mut dst) |
Convert to JSON (json feature) |
to_toml(&node, &mut dst) |
Convert to TOML (toml feature) |
to_xml(&node, &mut dst) |
Convert to XML (xml feature) |
to_yaml(&node, &mut dst) |
Convert to YAML (yaml feature) |
I/O
| Type | Description |
|---|---|
BufferSource |
Read Bencode from an in-memory buffer |
FileSource |
Read Bencode from a file (std feature) |
BufferDestination |
Write output to an in-memory buffer |
FileDestination |
Write output to a file (std feature) |
Node Methods
Type checking: is_integer(), is_string(), is_list(), is_dictionary(), is_none()
Value access: as_integer(), as_string(), as_list(), as_list_mut(), as_dictionary(), as_dictionary_mut()
Dictionary access: get(key), get_mut(key)
Validation helpers:
| Method | Returns |
|---|---|
get_required(key) |
Result<&Node, String> |
get_int_required(key) |
Result<i64, String> |
get_string_required(key) |
Result<&str, String> |
get_list_required(key) |
Result<&Vec<Node>, String> |
get_dict_required(key) |
Result<&HashMap<String, Node>, String> |
get_int_optional(key) |
Option<i64> |
get_string_optional(key) |
Option<&str> |
get_list_optional(key) |
Option<&Vec<Node>> |
get_dict_optional(key) |
Option<&HashMap<String, Node>> |
Utility: len(), is_empty(), type_name()
Embedded / no_std API
| Type / Function | Description |
|---|---|
Arena |
Bump allocator from a fixed buffer |
StackBuffer<N> |
Stack-allocated byte buffer |
MemoryTracker |
Allocation accounting for embedded systems |
FixedSizeBuffer<N> |
Stack-allocated fixed-size buffer (const generic) |
MemoryBounds |
Const-generic memory bounds calculator |
BorrowedNode |
Zero-copy borrowed node (no allocation) |
Configuration
use ;
let parser = new.with_max_depth; // default: 100
let encoder = new
.with_canonical // enforce sorted dict keys, no leading zeros
.with_dict_order_verification;
Utilities
| Function | Description |
|---|---|
version() |
Returns the library version string |
read_file(path) |
Read a file to String (std feature) → Result<String, io::Error> |
write_file(path, content) |
Write a string to a file (std feature) → Result<(), io::Error> |
Error Handling
BencodeError is a lightweight, allocation-free enum suitable for no_std environments:
Each variant exposes .code() -> u8 for compact logging and .as_str() -> &'static str for human-readable messages. In std environments, BencodeError implements std::error::Error.
Note:
read_file/write_filereturnstd::io::Error, notBencodeError.
Minimum Supported Rust Version
Rust 1.85.0 (edition 2024).
Documentation
See the Documentation Hub for complete guides:
- Embedded Systems Guide —
no_std, stack allocation, and memory bounds - Architecture Guide — 3-tier layering model and SOLID design
- Development Guide — contributing and project structure
- Security Policy — 64 MB length prefix limit and defenses
- Contributing Guidelines — pull requests and code standards
Support
If you find this project useful, you can support its development by buying me a coffee:
Or visit buymeacoffee.com/roberttizz1.
License
MIT License. See LICENSE for details.