[][src]Crate serde_bencoded

Yet another encoding/decoding library for bencode.

I believe deserializer don't allocate memory. Serializer allocates only when sort_dictionary feature enabled. Must be fast enough.

Examples

For .torrent parsing example see examples directory

Caveats

serde treats [u8; N], Vec<u8>, &[u8] like any other sequence, that is it will be encoded as list of bytes(not a byte string).

Sollution - use serde_bytes.

Behaviour

This crate does sort dictionary by keys if sort_dictionary feature is enabled (enabled by default). Otherwise order of elements can vary (depends on Serialize trait implementation).

Mapping of rust types to bencode

  • bool is integer either i1e or i0e.

  • all primiteve integer types is integer.

  • char is byte string with length at most 4 bytes.

  • String is byte string.

  • [u8] is list see Caveats.

  • Option is bencode value if Some otherwise nothing will be written.

  • () (unit) is 0:, empty byte string.

  • struct UnitStruct; is 10:UnitStruct, byte string containing name of the unit struct.

  • enum E { A, B }

    • E::A is d1:E1:Ae, dictionary with one entry. Key is name of the enum and value is the variant.
  • struct Wrapper(u8) (newtype struct) is bencode of the containing type.

  • tuples and arrays is lists, tuples can be heterogeneous.

  • struct Rgb(u8, u8, u8) (tuple struct) is list of tuple values.

  • HashMap is dictionary.

  • structs is dictionary. Keys are field names, values are field values.

  • f32, f64 is not supported.

Alternatives

Arbitrary order. Search more on crates.io or lib.rs.

Bencoding

Supported data types

Byte Strings

<base ten ASCII>:<string bytes>

Examples:

  • 4:abcd
  • 0:

Integers

i<base ten ASCII, optional minus sign>e

The maximum number is not specified. This crate handles integers as u64 or i64.

Examples:

  • i123456e
  • i-5e

Malformed:

  • i03e, anything that starts with 0, except i0e
  • i-0e

Lists

l<bencode type values>e

Examples:

  • li0ei1ei2ee == [1,2,3]
  • le == []

Dictionaries

d<bencoded string><bencoded element>e

Keys must be sorted as raw strings. string's should be compared using a binary comparison.

Examples:

  • de == {}
  • d4:rustl2:is7:awesomeee == {"rust" => ["is", "awesome"]}

Crate features

sort_dictionary

Enables sort by keys when serializing to bencode dictionary.

Structs

Deserializer
Serializer

Enums

DeError
SerError

Functions

from_bytes

Deserializes bencoded bytes to rust's value.

from_str

Deserializes bencoded &str to rust's value.

to_string

Serializes rust's type to bencode string

to_vec

Convenient function to get encoded value as bytes

to_writer

Serializes rust's type to bencode using Write trait

Type Definitions

DeResult
SerResult