bencode 0.1.15

Bencode library for easy encoding/decoding

Crate bencode [] [src]

Bencode parsing and serialization

Encoding

Using Encodable

extern crate rustc_serialize;
extern crate bencode;

use rustc_serialize::Encodable;

use bencode::encode;

#[derive(RustcEncodable)]
struct MyStruct {
    string: String,
    id: usize,
}

fn main() {
    let s = MyStruct { string: "Hello bencode".to_string(), id: 1 };
    let result: Vec<u8> = encode(&s).unwrap();
}

Using ToBencode

extern crate bencode;

use std::collections::BTreeMap;

use bencode::{Bencode, ToBencode};
use bencode::util::ByteString;

struct MyStruct {
    a: isize,
    b: String,
    c: Vec<u8>,
}

impl ToBencode for MyStruct {
    fn to_bencode(&self) -> bencode::Bencode {
        let mut m = BTreeMap::new();
        m.insert(ByteString::from_str("a"), self.a.to_bencode());
        m.insert(ByteString::from_str("b"), self.b.to_bencode());
        m.insert(ByteString::from_str("c"), Bencode::ByteString(self.c.to_vec()));
        Bencode::Dict(m)
    }
}

fn main() {
    let s = MyStruct{ a: 5, b: "foo".to_string(), c: vec![1, 2, 3, 4] };
    let bencode: bencode::Bencode = s.to_bencode();
    let result: Vec<u8> = bencode.to_bytes().unwrap();
}

Decoding

Using Decodable

extern crate rustc_serialize;
extern crate bencode;

use rustc_serialize::{Encodable, Decodable};

use bencode::{encode, Decoder};

#[derive(RustcEncodable, RustcDecodable, PartialEq)]
struct MyStruct {
    a: i32,
    b: String,
    c: Vec<u8>,
}

fn main() {
    let s = MyStruct{ a: 5, b: "foo".to_string(), c: vec![1, 2, 3, 4] };
    let enc: Vec<u8> = encode(&s).unwrap();

    let bencode: bencode::Bencode = bencode::from_vec(enc).unwrap();
    let mut decoder = Decoder::new(&bencode);
    let result: MyStruct = Decodable::decode(&mut decoder).unwrap();
    assert!(s == result)
}

Using FromBencode

extern crate bencode;

use std::collections::BTreeMap;

use bencode::{FromBencode, ToBencode, Bencode, NumFromBencodeError};
use bencode::util::ByteString;

#[derive(PartialEq)]
struct MyStruct {
    a: i32
}

#[derive(Debug)]
enum MyError {
    NotADict,
    DoesntContainA,
    ANotANumber(NumFromBencodeError),
}

impl ToBencode for MyStruct {
    fn to_bencode(&self) -> bencode::Bencode {
        let mut m = BTreeMap::new();
        m.insert(ByteString::from_str("a"), self.a.to_bencode());
        Bencode::Dict(m)
    }
}

impl FromBencode for MyStruct {
    type Err = MyError;

    fn from_bencode(bencode: &bencode::Bencode) -> Result<MyStruct, MyError> {
        use MyError::*;
        match bencode {
            &Bencode::Dict(ref m) => {
                match m.get(&ByteString::from_str("a")) {
                    Some(a) => FromBencode::from_bencode(a).map(|a| {
                        MyStruct{ a: a }
                    }).map_err(ANotANumber),
                    _ => Err(DoesntContainA)
                }
            }
            _ => Err(NotADict)
        }
    }
}

fn main() {
    let s = MyStruct{ a: 5 };
    let enc: Vec<u8>  = s.to_bencode().to_bytes().unwrap();

    let bencode: bencode::Bencode = bencode::from_vec(enc).unwrap();
    let result: MyStruct = FromBencode::from_bencode(&bencode).unwrap();
    assert!(s == result)
}

Using Streaming Parser

extern crate rustc_serialize;
extern crate bencode;

use bencode::streaming::BencodeEvent;
use bencode::streaming::StreamingParser;
use rustc_serialize::Encodable;

use bencode::encode;

#[derive(RustcEncodable, RustcDecodable, PartialEq)]
struct MyStruct {
    a: i32,
    b: String,
    c: Vec<u8>,
}

fn main() {
    let s = MyStruct{ a: 5, b: "foo".to_string(), c: vec![2, 2, 3, 4] };
    let enc: Vec<u8> = encode(&s).unwrap();

    let mut streaming = StreamingParser::new(enc.into_iter());
    for event in streaming {
        match event {
            BencodeEvent::DictStart => println!("dict start"),
            BencodeEvent::DictEnd => println!("dict end"),
            BencodeEvent::NumberValue(n) => println!("number = {}", n),
            // ...
            _ => println!("Unhandled event: {:?}", event)
        }
    }
}

Modules

streaming
util

Structs

Decoder
Encoder
Parser

Enums

Bencode
BoolFromBencodeError
CharFromBencodeError
DecoderError
FloatFromBencodeError
MapFromBencodeError
NumFromBencodeError
StringFromBencodeError
VecFromBencodeError

Traits

FromBencode
ToBencode

Functions

encode
from_buffer
from_iter
from_vec

Type Definitions

DecoderResult
DictMap
EncoderResult
ListVec