add utility methods to the bencode objects

This commit is contained in:
2016-12-11 19:15:09 -05:00
parent 0fc6704cc2
commit bd021f80a3
3 changed files with 175 additions and 32 deletions

View File

@@ -1,7 +1,6 @@
use std::borrow::Borrow;
use std::collections::BTreeMap;
use bencode::Object;
use bencode::{Dict, Object};
pub fn encode<B>(obj: B) -> Vec<u8> where B: Borrow<Object> {
let mut buff = Vec::new();
@@ -35,9 +34,9 @@ fn encode_list(buff: &mut Vec<u8>, list: &[Object]) {
buff.push(b'e');
}
fn encode_dict(buff: &mut Vec<u8>, dict: &BTreeMap<Vec<u8>, Object>) {
fn encode_dict(buff: &mut Vec<u8>, dict: &Dict) {
buff.push(b'd');
for (key, val) in dict {
for (key, val) in dict.iter() {
encode_bytes(buff, key);
encode_object(buff, val);
}
@@ -56,18 +55,25 @@ fn test_int_neg() {
#[test]
fn test_bytes() {
assert_eq!(encode(Object::Bytes(b"hello".to_vec())), b"5:hello");
use bencode::Bytes;
assert_eq!(encode(Bytes::new(b"hello".to_vec())), 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(Object::List(list)), b"li1ei2ei3ee");
assert_eq!(encode(List::new(list)), b"li1ei2ei3ee");
}
#[test]
fn test_dict() {
use std::collections::BTreeMap;
use bencode::{Bytes, Dict};
let mut dict = BTreeMap::new();
dict.insert(b"hello".to_vec(), Object::Int(1337));
assert_eq!(encode(Object::Dict(dict)), b"d5:helloi1337ee")
dict.insert(Bytes(b"hello".to_vec()), Object::Int(1337));
assert_eq!(encode(Dict::new(dict)), b"d5:helloi1337ee")
}