#codec #enums #bencode #deserialize #decoder #encoder #rustc-serialize

simple_bencode

Simple bencode encoder and decoder, that uses neither rustc-serialize or Serde. Instead, it serializes from / deserializes to a tree using a 4-branch enum.

5 releases

Uses old Rust 2015

0.1.4 Dec 31, 2016
0.1.3 Dec 26, 2016
0.1.2 Dec 26, 2016
0.1.1 Dec 26, 2016
0.1.0 Dec 26, 2016

#2080 in Encoding

22 downloads per month
Used in fcp_switching

MIT license

15KB
298 lines

rust-simple-bencode

Simple bencode encoder and decoder, that uses neither rustc-serialize or Serde. Instead, it serializes from / deserializes to a tree using a 4-branch enum."

Basic usage

This library is mainly composed of the read and write function, which serialize from and deserialize to this enum:

pub enum Value {
    String(Vec<u8>),
    Integer(i64),
    List(Vec<Value>),
    Dictionary(HashMap<Vec<u8>, Value>),
}

The signature of these functions are:

pub fn read<R: io::Read>(bytes: &mut Peekable<io::Bytes<R>>) -> Result<Value, DecodeError>;
pub fn write<W: io::Write>(v: &Value, writer: &mut W) -> Result<(), io::Error>;

where DecodeError is defined like this:

pub enum DecodeError {
    IOError(io::Error),
    UnexpectedEndOfBuffer,
    UnexpectedCharacter(String)
}

Working with byte arrays

If you work with byte arrays, these shortcuts should be useful to you:

pub fn decode(sl: &[u8]) -> Result<Value, DecodeError>;
pub fn encode(v: &Value) -> Vec<u8>;

## Helpers to deal with Value

Because some operations to read Value are common, this library provides helpers to avoid error-handling boilerplate:

pub enum HelperDecodeError {
    BencodeDecodeError(DecodeError),
    BadType(String),
    MissingKey(String),
    FromUtf8Error(FromUtf8Error),
}

/// Pops a BValue::Integer from a HashMap.
pub fn pop_value_integer(map: &mut HashMap<Vec<u8>, Value>, key: String) -> Result<i64, HelperDecodeError>;

/// Pops a BValue::String from a HashMap.
pub fn pop_value_bytestring(map: &mut HashMap<Vec<u8>, Value>, key: String) -> Result<Vec<u8>, HelperDecodeError>;

/// Pops an optional BValue::String from a HashMap.
pub fn pop_value_bytestring_option(map: &mut HashMap<Vec<u8>, Value>, key: String) -> Result<Option<Vec<u8>>, HelperDecodeError>;

/// Pops a BValue::String from a HashMap and decode it into a Rust String.
pub fn pop_value_utf8_string(map: &mut HashMap<Vec<u8>, Value>, key: String) -> Result<String, HelperDecodeError>;

/// Pops an optional BValue::String from a HashMap and decode it into a Rust String.
pub fn pop_value_utf8_string_option(map: &mut HashMap<Vec<u8>, Value>, key: String) -> Result<Option<String>, HelperDecodeError>;

No runtime deps