cache item count in Rlp

This commit is contained in:
arkpar 2015-12-22 22:23:01 +01:00
parent 900fc833f0
commit f34b22c65b
2 changed files with 24 additions and 14 deletions

View File

@ -49,14 +49,16 @@ impl PayloadInfo {
#[derive(Debug)] #[derive(Debug)]
pub struct UntrustedRlp<'a> { pub struct UntrustedRlp<'a> {
bytes: &'a [u8], bytes: &'a [u8],
cache: Cell<OffsetCache>, offset_cache: Cell<OffsetCache>,
count_cache: Cell<Option<usize>>,
} }
impl<'a> Clone for UntrustedRlp<'a> { impl<'a> Clone for UntrustedRlp<'a> {
fn clone(&self) -> UntrustedRlp<'a> { fn clone(&self) -> UntrustedRlp<'a> {
UntrustedRlp { UntrustedRlp {
bytes: self.bytes, bytes: self.bytes,
cache: Cell::new(OffsetCache::new(usize::max_value(), 0)) offset_cache: self.offset_cache.clone(),
count_cache: self.count_cache.clone(),
} }
} }
} }
@ -72,7 +74,8 @@ impl<'a, 'view> View<'a, 'view> for UntrustedRlp<'a> where 'a: 'view {
fn new(bytes: &'a [u8]) -> UntrustedRlp<'a> { fn new(bytes: &'a [u8]) -> UntrustedRlp<'a> {
UntrustedRlp { UntrustedRlp {
bytes: bytes, bytes: bytes,
cache: Cell::new(OffsetCache::new(usize::max_value(), 0)), offset_cache: Cell::new(OffsetCache::new(usize::max_value(), 0)),
count_cache: Cell::new(None)
} }
} }
@ -102,7 +105,14 @@ impl<'a, 'view> View<'a, 'view> for UntrustedRlp<'a> where 'a: 'view {
fn item_count(&self) -> usize { fn item_count(&self) -> usize {
match self.is_list() { match self.is_list() {
true => self.iter().count(), true => match self.count_cache.get() {
Some(c) => c,
None => {
let c = self.iter().count();
self.count_cache.set(Some(c));
c
}
},
false => 0 false => 0
} }
} }
@ -122,7 +132,7 @@ impl<'a, 'view> View<'a, 'view> for UntrustedRlp<'a> where 'a: 'view {
// move to cached position if it's index is less or equal to // move to cached position if it's index is less or equal to
// current search index, otherwise move to beginning of list // current search index, otherwise move to beginning of list
let c = self.cache.get(); let c = self.offset_cache.get();
let (mut bytes, to_skip) = match c.index <= index { let (mut bytes, to_skip) = match c.index <= index {
true => (try!(UntrustedRlp::consume(self.bytes, c.offset)), index - c.index), true => (try!(UntrustedRlp::consume(self.bytes, c.offset)), index - c.index),
false => (try!(self.consume_list_prefix()), index), false => (try!(self.consume_list_prefix()), index),
@ -132,7 +142,7 @@ impl<'a, 'view> View<'a, 'view> for UntrustedRlp<'a> where 'a: 'view {
bytes = try!(UntrustedRlp::consume_items(bytes, to_skip)); bytes = try!(UntrustedRlp::consume_items(bytes, to_skip));
// update the cache // update the cache
self.cache.set(OffsetCache::new(index, self.bytes.len() - bytes.len())); self.offset_cache.set(OffsetCache::new(index, self.bytes.len() - bytes.len()));
// construct new rlp // construct new rlp
let found = try!(BasicDecoder::payload_info(bytes)); let found = try!(BasicDecoder::payload_info(bytes));