refactor and simplify the bencode objects

This commit is contained in:
2016-12-11 22:00:31 -05:00
parent 881c1e2b01
commit 72d4dfc0b8
4 changed files with 171 additions and 88 deletions

View File

@@ -1,10 +1,28 @@
use std::borrow::Borrow;
use std::borrow::Cow;
use bencode::{Dict, Object};
pub fn encode<B>(obj: B) -> Vec<u8> where B: Borrow<Object> {
/// Allows the encode function to take something that can be converted into an object,
/// or a reference to an object.
pub trait Encodable<'a> {
fn get_object(self) -> Cow<'a, Object>;
}
impl<'a, T> Encodable<'a> for T where T: Into<Object> {
fn get_object(self) -> Cow<'a, Object> {
Cow::Owned(self.into())
}
}
impl<'a> Encodable<'a> for &'a Object {
fn get_object(self) -> Cow<'a, Object> {
Cow::Borrowed(self)
}
}
pub fn encode<'a, O>(obj: O) -> Vec<u8> where O: Encodable<'a> {
let mut buff = Vec::new();
encode_object(&mut buff, obj.borrow());
encode_object(&mut buff, &obj.get_object());
buff
}
@@ -45,35 +63,30 @@ fn encode_dict(buff: &mut Vec<u8>, dict: &Dict) {
#[test]
fn test_int_pos() {
assert_eq!(encode(Object::Int(1337)), b"i1337e");
assert_eq!(encode(1337), b"i1337e");
}
#[test]
fn test_int_neg() {
assert_eq!(encode(Object::Int(-1337)), b"i-1337e");
assert_eq!(encode(-1337), b"i-1337e");
}
#[test]
fn test_bytes() {
use bencode::Bytes;
assert_eq!(encode(Bytes::wrap(b"hello".to_vec())), b"5:hello");
assert_eq!(encode("hello"), b"5:hello");
}
#[test]
fn test_list() {
use bencode::List;
let list = vec![Object::Int(1), Object::Int(2), Object::Int(3)];
assert_eq!(encode(List::wrap(list)), b"li1ei2ei3ee");
assert_eq!(encode(list), b"li1ei2ei3ee");
}
#[test]
fn test_dict() {
use std::collections::BTreeMap;
use bencode::{Bytes, Dict};
use bencode::Dict;
let mut dict = BTreeMap::new();
dict.insert(Bytes(b"hello".to_vec()), Object::Int(1337));
assert_eq!(encode(Dict::wrap(dict)), b"d5:helloi1337ee")
let mut dict = Dict::new();
dict.insert("hello", 1337);
assert_eq!(encode(dict), b"d5:helloi1337ee")
}