formatted rlp.rs

This commit is contained in:
debris 2015-11-27 20:59:28 +01:00
parent 1eacff7e3d
commit f8bd7da111
1 changed files with 607 additions and 569 deletions

View File

@ -54,31 +54,37 @@ use vector::InsertSlice;
#[derive(Debug)]
pub struct Rlp<'a> {
bytes: &'a [u8],
cache: Cell<OffsetCache>
cache: Cell<OffsetCache>,
}
/// rlp offset
#[derive(Copy, Clone, Debug)]
struct OffsetCache {
index: usize,
offset: usize
offset: usize,
}
impl OffsetCache {
fn new(index: usize, offset: usize) -> OffsetCache {
OffsetCache { index: index, offset: offset }
OffsetCache {
index: index,
offset: offset,
}
}
}
/// stores basic information about item
struct ItemInfo {
prefix_len: usize,
value_len: usize
value_len: usize,
}
impl ItemInfo {
fn new(prefix_len: usize, value_len: usize) -> ItemInfo {
ItemInfo { prefix_len: prefix_len, value_len: value_len }
ItemInfo {
prefix_len: prefix_len,
value_len: value_len,
}
}
}
@ -91,7 +97,9 @@ pub enum DecoderError {
BadRlp,
}
impl StdError for DecoderError {
fn description(&self) -> &str { "builder error" }
fn description(&self) -> &str {
"builder error"
}
}
impl fmt::Display for DecoderError {
@ -101,7 +109,9 @@ impl fmt::Display for DecoderError {
}
impl From<FromBytesError> for DecoderError {
fn from(err: FromBytesError) -> DecoderError { DecoderError::FromBytesError(err) }
fn from(err: FromBytesError) -> DecoderError {
DecoderError::FromBytesError(err)
}
}
impl<'a> Rlp<'a> {
@ -109,7 +119,7 @@ impl <'a>Rlp<'a> {
pub fn new(bytes: &'a [u8]) -> Rlp<'a> {
Rlp {
bytes: bytes,
cache: Cell::new(OffsetCache::new(usize::max_value(), 0))
cache: Cell::new(OffsetCache::new(usize::max_value(), 0)),
}
}
@ -126,7 +136,7 @@ impl <'a>Rlp<'a> {
let c = self.cache.get();
let (mut bytes, to_skip) = match c.index <= index {
true => (try!(Rlp::consume(self.bytes, c.offset)), index - c.index),
false => (try!(self.consume_list_prefix()), index)
false => (try!(self.consume_list_prefix()), index),
};
// skip up to x items
@ -190,13 +200,13 @@ impl <'a>Rlp<'a> {
let prefix_len = 1 + len_of_len;
let value_len = try!(usize::from_bytes(&bytes[1..prefix_len]));
ItemInfo::new(prefix_len, value_len)
},
_ => return Err(DecoderError::BadRlp)
}
_ => return Err(DecoderError::BadRlp),
};
match item.prefix_len + item.value_len <= bytes.len() {
true => Ok(item),
false => Err(DecoderError::RlpIsTooShort)
false => Err(DecoderError::RlpIsTooShort),
}
}
@ -204,7 +214,7 @@ impl <'a>Rlp<'a> {
fn consume(bytes: &'a [u8], len: usize) -> Result<&'a [u8], DecoderError> {
match bytes.len() >= len {
true => Ok(&bytes[len..]),
false => Err(DecoderError::RlpIsTooShort)
false => Err(DecoderError::RlpIsTooShort),
}
}
}
@ -212,7 +222,7 @@ impl <'a>Rlp<'a> {
/// non-consuming rlp iterator
pub struct RlpIterator<'a> {
rlp: &'a Rlp<'a>,
index: usize
index: usize,
}
impl<'a> IntoIterator for &'a Rlp<'a> {
@ -220,7 +230,10 @@ impl <'a> IntoIterator for &'a Rlp<'a> {
type IntoIter = RlpIterator<'a>;
fn into_iter(self) -> Self::IntoIter {
RlpIterator { rlp: self, index: 0 }
RlpIterator {
rlp: self,
index: 0,
}
}
}
@ -236,7 +249,9 @@ impl <'a> Iterator for RlpIterator<'a> {
}
/// shortcut function to decode a Rlp `&[u8]` into an object
pub fn decode<T>(bytes: &[u8]) -> Result<T, DecoderError> where T: Decodable {
pub fn decode<T>(bytes: &[u8]) -> Result<T, DecoderError>
where T: Decodable
{
let rlp = Rlp::new(bytes);
T::decode(&rlp)
}
@ -245,20 +260,22 @@ pub trait Decodable: Sized {
fn decode(rlp: &Rlp) -> Result<Self, DecoderError>;
}
impl <T> Decodable for T where T: FromBytes {
impl<T> Decodable for T where T: FromBytes
{
fn decode(rlp: &Rlp) -> Result<Self, DecoderError> {
match rlp.is_value() {
true => BasicDecoder::read_value(rlp.bytes),
false => Err(DecoderError::RlpExpectedToBeValue)
false => Err(DecoderError::RlpExpectedToBeValue),
}
}
}
impl <T> Decodable for Vec<T> where T: Decodable {
impl<T> Decodable for Vec<T> where T: Decodable
{
fn decode(rlp: &Rlp) -> Result<Self, DecoderError> {
match rlp.is_list() {
true => rlp.iter().map(|rlp| T::decode(&rlp)).collect(),
false => Err(DecoderError::RlpExpectedToBeList)
false => Err(DecoderError::RlpExpectedToBeList),
}
}
}
@ -270,7 +287,9 @@ pub trait Decoder {
struct BasicDecoder;
impl Decoder for BasicDecoder {
fn read_value<T>(bytes: &[u8]) -> Result<T, DecoderError> where T: FromBytes {
fn read_value<T>(bytes: &[u8]) -> Result<T, DecoderError>
where T: FromBytes
{
match bytes.first().map(|&x| x) {
// rlp is too short
None => Err(DecoderError::RlpIsTooShort),
@ -284,8 +303,8 @@ impl Decoder for BasicDecoder {
let begin_of_value = 1 as usize + len_of_len;
let len = try!(usize::from_bytes(&bytes[1..begin_of_value]));
Ok(try!(T::from_bytes(&bytes[begin_of_value..begin_of_value + len])))
},
_ => Err(DecoderError::BadRlp)
}
_ => Err(DecoderError::BadRlp),
}
}
}
@ -294,7 +313,7 @@ impl Decoder for BasicDecoder {
struct ListInfo {
position: usize,
current: usize,
max: usize
max: usize,
}
impl ListInfo {
@ -302,7 +321,7 @@ impl ListInfo {
ListInfo {
position: position,
current: 0,
max: max
max: max,
}
}
}
@ -310,7 +329,7 @@ impl ListInfo {
/// container that should be used to encode rlp
pub struct RlpStream {
unfinished_lists: LinkedList<ListInfo>,
encoder: BasicEncoder
encoder: BasicEncoder,
}
impl RlpStream {
@ -319,7 +338,7 @@ impl RlpStream {
pub fn new() -> RlpStream {
RlpStream {
unfinished_lists: LinkedList::new(),
encoder: BasicEncoder::new()
encoder: BasicEncoder::new(),
}
}
@ -331,7 +350,9 @@ impl RlpStream {
}
/// apends value to the end of stream, chainable
pub fn append<'a, E>(&'a mut self, object: &E) -> &'a mut RlpStream where E: Encodable {
pub fn append<'a, E>(&'a mut self, object: &E) -> &'a mut RlpStream
where E: Encodable
{
// encode given value and add it at the end of the stream
object.encode(&mut self.encoder);
@ -351,8 +372,8 @@ impl RlpStream {
// we may finish, if the appended list len is equal 0
self.encoder.bytes.push(0xc0u8);
self.try_to_finish();
},
_ => self.unfinished_lists.push_back(ListInfo::new(position, len))
}
_ => self.unfinished_lists.push_back(ListInfo::new(position, len)),
}
// return chainable self
@ -368,7 +389,7 @@ impl RlpStream {
pub fn out(self) -> Result<Vec<u8>, EncoderError> {
match self.is_finished() {
true => Ok(self.encoder.out()),
false => Err(EncoderError::StreamIsUnfinished)
false => Err(EncoderError::StreamIsUnfinished),
}
}
@ -392,7 +413,9 @@ impl RlpStream {
}
/// shortcut function to encode a `T: Encodable` into a Rlp `Vec<u8>`
pub fn encode<E>(object: &E) -> Vec<u8> where E: Encodable {
pub fn encode<E>(object: &E) -> Vec<u8>
where E: Encodable
{
let mut encoder = BasicEncoder::new();
object.encode(&mut encoder);
encoder.out()
@ -400,11 +423,13 @@ pub fn encode<E>(object: &E) -> Vec<u8> where E: Encodable {
#[derive(Debug)]
pub enum EncoderError {
StreamIsUnfinished
StreamIsUnfinished,
}
impl StdError for EncoderError {
fn description(&self) -> &str { "encoder error" }
fn description(&self) -> &str {
"encoder error"
}
}
impl fmt::Display for EncoderError {
@ -422,14 +447,20 @@ pub trait Encoder {
fn emit_list<F>(&mut self, f: F) -> () where F: FnOnce(&mut Self) -> ();
}
impl <T> Encodable for T where T: ToBytes {
fn encode<E>(&self, encoder: &mut E) -> () where E: Encoder {
impl<T> Encodable for T where T: ToBytes
{
fn encode<E>(&self, encoder: &mut E) -> ()
where E: Encoder
{
encoder.emit_value(&self.to_bytes())
}
}
impl <'a, T> Encodable for &'a [T] where T: Encodable + 'a {
fn encode<E>(&self, encoder: &mut E) -> () where E: Encoder {
impl<'a, T> Encodable for &'a [T] where T: Encodable + 'a
{
fn encode<E>(&self, encoder: &mut E) -> ()
where E: Encoder
{
encoder.emit_list(|e| {
// insert all list elements
for el in self.iter() {
@ -439,15 +470,18 @@ impl <'a, T> Encodable for &'a [T] where T: Encodable + 'a {
}
}
impl <T> Encodable for Vec<T> where T: Encodable {
fn encode<E>(&self, encoder: &mut E) -> () where E: Encoder {
impl<T> Encodable for Vec<T> where T: Encodable
{
fn encode<E>(&self, encoder: &mut E) -> ()
where E: Encoder
{
let r: &[T] = self.as_ref();
r.encode(encoder)
}
}
struct BasicEncoder {
bytes: Vec<u8>
bytes: Vec<u8>,
}
impl BasicEncoder {
@ -497,7 +531,9 @@ impl Encoder for BasicEncoder {
}
}
fn emit_list<F>(&mut self, f: F) -> () where F: FnOnce(&mut Self) -> () {
fn emit_list<F>(&mut self, f: F) -> ()
where F: FnOnce(&mut Self) -> ()
{
// get len before inserting a list
let before_len = self.bytes.len();
@ -527,7 +563,8 @@ mod tests {
{
let rlp = Rlp::new(&data);
assert!(rlp.is_list());
let animals = <Vec<String> as rlp::Decodable>::decode(&rlp).unwrap();
let animals =
<Vec<String> as rlp::Decodable>::decode(&rlp).unwrap();
assert_eq!(animals, vec!["cat".to_string(), "dog".to_string()]);
let cat = rlp.at(0).unwrap();
@ -588,7 +625,9 @@ mod tests {
struct ETestPair<T>(T, Vec<u8>) where T: rlp::Encodable;
fn run_encode_tests<T>(tests: Vec<ETestPair<T>>) where T: rlp::Encodable {
fn run_encode_tests<T>(tests: Vec<ETestPair<T>>)
where T: rlp::Encodable
{
for t in &tests {
let res = rlp::encode(&t.0);
assert_eq!(res, &t.1[..]);
@ -641,34 +680,34 @@ mod tests {
#[test]
fn encode_u256() {
let tests = vec![
ETestPair(U256::from(0u64), vec![0x80u8]),
let tests = vec![ETestPair(U256::from(0u64), vec![0x80u8]),
ETestPair(U256::from(0x1000000u64), vec![0x84, 0x01, 0x00, 0x00, 0x00]),
ETestPair(U256::from(0xffffffffu64), vec![0x84, 0xff, 0xff, 0xff, 0xff]),
ETestPair(U256::from_str("8090a0b0c0d0e0f00910203040506077000000000000000100000000000012f0").unwrap(),
ETestPair(U256::from(0xffffffffu64),
vec![0x84, 0xff, 0xff, 0xff, 0xff]),
ETestPair(U256::from_str("8090a0b0c0d0e0f00910203040506077000000000000\
000100000000000012f0")
.unwrap(),
vec![0xa0, 0x80, 0x90, 0xa0, 0xb0, 0xc0, 0xd0, 0xe0, 0xf0,
0x09, 0x10, 0x20, 0x30, 0x40, 0x50, 0x60, 0x77,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x12, 0xf0])
];
0x09, 0x10, 0x20, 0x30, 0x40, 0x50, 0x60, 0x77, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x12, 0xf0])];
run_encode_tests(tests);
}
#[test]
fn encode_str() {
let tests = vec![
ETestPair("cat", vec![0x83, b'c', b'a', b't']),
let tests = vec![ETestPair("cat", vec![0x83, b'c', b'a', b't']),
ETestPair("dog", vec![0x83, b'd', b'o', b'g']),
ETestPair("Marek", vec![0x85, b'M', b'a', b'r', b'e', b'k']),
ETestPair("", vec![0x80]),
ETestPair("Lorem ipsum dolor sit amet, consectetur adipisicing elit",
vec![0xb8, 0x38, b'L', b'o', b'r', b'e', b'm', b' ', b'i',
b'p', b's', b'u', b'm', b' ', b'd', b'o', b'l', b'o', b'r',
b' ', b's', b'i', b't', b' ', b'a', b'm', b'e', b't', b',',
b' ', b'c', b'o', b'n', b's', b'e', b'c', b't', b'e', b't',
b'u', b'r', b' ', b'a', b'd', b'i', b'p', b'i', b's', b'i',
b'c', b'i', b'n', b'g', b' ', b'e', b'l', b'i', b't'])
];
b'p', b's', b'u', b'm', b' ', b'd', b'o', b'l', b'o',
b'r', b' ', b's', b'i', b't', b' ', b'a', b'm', b'e',
b't', b',', b' ', b'c', b'o', b'n', b's', b'e', b'c',
b't', b'e', b't', b'u', b'r', b' ', b'a', b'd', b'i',
b'p', b'i', b's', b'i', b'c', b'i', b'n', b'g', b' ',
b'e', b'l', b'i', b't'])];
run_encode_tests(tests);
}
@ -695,17 +734,14 @@ mod tests {
#[test]
fn encode_vector_str() {
let tests = vec![
ETestPair(vec!["cat", "dog"], vec![0xc8, 0x83, b'c', b'a', b't', 0x83, b'd', b'o', b'g'])
];
let tests = vec![ETestPair(vec!["cat", "dog"],
vec![0xc8, 0x83, b'c', b'a', b't', 0x83, b'd', b'o', b'g'])];
run_encode_tests(tests);
}
#[test]
fn encode_vector_of_vectors_str() {
let tests = vec![
ETestPair(vec![vec!["cat"]], vec![0xc5, 0xc4, 0x83, b'c', b'a', b't'])
];
let tests = vec![ETestPair(vec![vec!["cat"]], vec![0xc5, 0xc4, 0x83, b'c', b'a', b't'])];
run_encode_tests(tests);
}
@ -714,7 +750,8 @@ mod tests {
let mut stream = RlpStream::new_list(2);
stream.append(&"cat").append(&"dog");
let out = stream.out().unwrap();
assert_eq!(out, vec![0xc8, 0x83, b'c', b'a', b't', 0x83, b'd', b'o', b'g']);
assert_eq!(out,
vec![0xc8, 0x83, b'c', b'a', b't', 0x83, b'd', b'o', b'g']);
}
#[test]
@ -729,7 +766,9 @@ mod tests {
struct DTestPair<T>(T, Vec<u8>) where T: rlp::Decodable + fmt::Debug + cmp::Eq;
fn run_decode_tests<T>(tests: Vec<DTestPair<T>>) where T: rlp::Decodable + fmt::Debug + cmp::Eq {
fn run_decode_tests<T>(tests: Vec<DTestPair<T>>)
where T: rlp::Decodable + fmt::Debug + cmp::Eq
{
for t in &tests {
let res: T = rlp::decode(&t.1).unwrap();
assert_eq!(res, t.0);
@ -782,34 +821,36 @@ mod tests {
#[test]
fn decode_u256() {
let tests = vec![
DTestPair(U256::from(0u64), vec![0x80u8]),
let tests = vec![DTestPair(U256::from(0u64), vec![0x80u8]),
DTestPair(U256::from(0x1000000u64), vec![0x84, 0x01, 0x00, 0x00, 0x00]),
DTestPair(U256::from(0xffffffffu64), vec![0x84, 0xff, 0xff, 0xff, 0xff]),
DTestPair(U256::from_str("8090a0b0c0d0e0f00910203040506077000000000000000100000000000012f0").unwrap(),
DTestPair(U256::from(0xffffffffu64),
vec![0x84, 0xff, 0xff, 0xff, 0xff]),
DTestPair(U256::from_str("8090a0b0c0d0e0f00910203040506077000000000000\
000100000000000012f0")
.unwrap(),
vec![0xa0, 0x80, 0x90, 0xa0, 0xb0, 0xc0, 0xd0, 0xe0, 0xf0,
0x09, 0x10, 0x20, 0x30, 0x40, 0x50, 0x60, 0x77,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x12, 0xf0])
];
0x09, 0x10, 0x20, 0x30, 0x40, 0x50, 0x60, 0x77, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x12, 0xf0])];
run_decode_tests(tests);
}
#[test]
fn decode_str() {
let tests = vec![
DTestPair("cat".to_string(), vec![0x83, b'c', b'a', b't']),
let tests = vec![DTestPair("cat".to_string(), vec![0x83, b'c', b'a', b't']),
DTestPair("dog".to_string(), vec![0x83, b'd', b'o', b'g']),
DTestPair("Marek".to_string(), vec![0x85, b'M', b'a', b'r', b'e', b'k']),
DTestPair("Marek".to_string(),
vec![0x85, b'M', b'a', b'r', b'e', b'k']),
DTestPair("".to_string(), vec![0x80]),
DTestPair("Lorem ipsum dolor sit amet, consectetur adipisicing elit".to_string(),
DTestPair("Lorem ipsum dolor sit amet, consectetur adipisicing elit"
.to_string(),
vec![0xb8, 0x38, b'L', b'o', b'r', b'e', b'm', b' ', b'i',
b'p', b's', b'u', b'm', b' ', b'd', b'o', b'l', b'o', b'r',
b' ', b's', b'i', b't', b' ', b'a', b'm', b'e', b't', b',',
b' ', b'c', b'o', b'n', b's', b'e', b'c', b't', b'e', b't',
b'u', b'r', b' ', b'a', b'd', b'i', b'p', b'i', b's', b'i',
b'c', b'i', b'n', b'g', b' ', b'e', b'l', b'i', b't'])
];
b'p', b's', b'u', b'm', b' ', b'd', b'o', b'l', b'o',
b'r', b' ', b's', b'i', b't', b' ', b'a', b'm', b'e',
b't', b',', b' ', b'c', b'o', b'n', b's', b'e', b'c',
b't', b'e', b't', b'u', b'r', b' ', b'a', b'd', b'i',
b'p', b'i', b's', b'i', b'c', b'i', b'n', b'g', b' ',
b'e', b'l', b'i', b't'])];
run_decode_tests(tests);
}
@ -836,18 +877,15 @@ mod tests {
#[test]
fn decode_vector_str() {
let tests = vec![
DTestPair(vec!["cat".to_string(), "dog".to_string()], vec![0xc8, 0x83, b'c', b'a', b't', 0x83, b'd', b'o', b'g'])
];
let tests = vec![DTestPair(vec!["cat".to_string(), "dog".to_string()],
vec![0xc8, 0x83, b'c', b'a', b't', 0x83, b'd', b'o', b'g'])];
run_decode_tests(tests);
}
#[test]
fn decode_vector_of_vectors_str() {
let tests = vec![
DTestPair(vec![vec!["cat".to_string()]], vec![0xc5, 0xc4, 0x83, b'c', b'a', b't'])
];
let tests = vec![DTestPair(vec![vec!["cat".to_string()]],
vec![0xc5, 0xc4, 0x83, b'c', b'a', b't'])];
run_decode_tests(tests);
}
}