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

@@ -2,7 +2,7 @@ use std::collections::BTreeMap;
use std::num::ParseIntError;
use std::str::{self, Utf8Error};
use bencode::Object;
use bencode::{Bytes, Dict, List, Object};
use buffer::Buffer;
#[derive(Debug)]
@@ -46,7 +46,7 @@ fn decode_object(buf: &mut Buffer) -> DecodeResult<Object> {
}
list.push(decode_object(buf)?);
}
Ok(Object::List(list))
Ok(List::new(list))
}
Some(b'd') => {
buf.advance(1);
@@ -58,9 +58,9 @@ fn decode_object(buf: &mut Buffer) -> DecodeResult<Object> {
}
let key = _decode_bytes(buf)?;
let val = decode_object(buf)?;
dict.insert(key, val);
dict.insert(Bytes(key), val);
}
Ok(Object::Dict(dict))
Ok(Dict::new(dict))
}
_ => Err(DecodeError),
}
@@ -84,7 +84,7 @@ fn _decode_int(buf: &mut Buffer, term: u8) -> DecodeResult<i64> {
}
fn decode_bytes(buf: &mut Buffer) -> DecodeResult<Object> {
_decode_bytes(buf).map(|bytes| Object::Bytes(bytes))
_decode_bytes(buf).map(|bytes| Bytes::new(bytes))
}
fn _decode_bytes(buf: &mut Buffer) -> Result<Vec<u8>, DecodeError> {
@@ -116,7 +116,7 @@ fn test_int_neg() {
fn test_bytes() {
let mut buf = Buffer::new(b"5:hello");
assert_eq!(decode_bytes(&mut buf).unwrap(), Object::Bytes(b"hello".to_vec()));
assert_eq!(decode_bytes(&mut buf).unwrap(), Bytes::new(b"hello".to_vec()));
assert_eq!(buf.pos(), 7);
}
@@ -127,7 +127,7 @@ fn test_list() {
let obj = decode_object(&mut buf).unwrap();
let list = obj.as_list().unwrap();
assert_eq!(list, vec![Object::Int(1), Object::Int(2), Object::Int(3)]);
assert_eq!(list, &List(vec![Object::Int(1), Object::Int(2), Object::Int(3)]));
assert_eq!(buf.pos(), 11);
}
@@ -138,6 +138,6 @@ fn test_dict() {
let obj = decode_object(&mut buf).unwrap();
let dict = obj.as_dict().unwrap();
assert_eq!(dict[&b"hello"[..]], Object::Int(1337));
assert_eq!(dict.get_int("hello").unwrap(), 1337);
assert_eq!(buf.pos(), 15);
}