optimized memorydb insert, remove and emplace

This commit is contained in:
debris 2017-08-26 18:34:16 +02:00
parent 5d6c53c9bd
commit 9083923f27

View File

@ -181,7 +181,10 @@ impl HashDB for MemoryDB {
} }
fn keys(&self) -> HashMap<H256, i32> { fn keys(&self) -> HashMap<H256, i32> {
self.data.iter().filter_map(|(k, v)| if v.1 != 0 {Some((k.clone(), v.1))} else {None}).collect() self.data.iter()
.filter(|&(_, v)| v.1 != 0)
.map(|(k, v)| (*k, v.1))
.collect()
} }
fn contains(&self, key: &H256) -> bool { fn contains(&self, key: &H256) -> bool {
@ -200,16 +203,17 @@ impl HashDB for MemoryDB {
return SHA3_NULL_RLP.clone(); return SHA3_NULL_RLP.clone();
} }
let key = value.sha3(); let key = value.sha3();
if match self.data.get_mut(&key) { match self.data.entry(key) {
Some(&mut (ref mut old_value, ref mut rc @ -0x80000000i32 ... 0)) => { Entry::Occupied(mut entry) => {
let &mut (ref mut old_value, ref mut rc) = entry.get_mut();
if *rc >= -0x80000000i32 && *rc <= 0 {
*old_value = DBValue::from_slice(value); *old_value = DBValue::from_slice(value);
}
*rc += 1; *rc += 1;
false
}, },
Some(&mut (_, ref mut x)) => { *x += 1; false } , Entry::Vacant(entry) => {
None => true, entry.insert((DBValue::from_slice(value), 1));
}{ // ... None falls through into... },
self.data.insert(key.clone(), (DBValue::from_slice(value), 1));
} }
key key
} }
@ -219,17 +223,18 @@ impl HashDB for MemoryDB {
return; return;
} }
match self.data.get_mut(&key) { match self.data.entry(key) {
Some(&mut (ref mut old_value, ref mut rc @ -0x80000000i32 ... 0)) => { Entry::Occupied(mut entry) => {
let &mut (ref mut old_value, ref mut rc) = entry.get_mut();
if *rc >= -0x80000000i32 && *rc <= 0 {
*old_value = value; *old_value = value;
*rc += 1;
return;
},
Some(&mut (_, ref mut x)) => { *x += 1; return; } ,
None => {},
} }
// ... None falls through into... *rc += 1;
self.data.insert(key, (value, 1)); },
Entry::Vacant(entry) => {
entry.insert((value, 1));
},
}
} }
fn remove(&mut self, key: &H256) { fn remove(&mut self, key: &H256) {
@ -237,11 +242,14 @@ impl HashDB for MemoryDB {
return; return;
} }
if match self.data.get_mut(key) { match self.data.entry(*key) {
Some(&mut (_, ref mut x)) => { *x -= 1; false } Entry::Occupied(mut entry) => {
None => true let &mut (_, ref mut rc) = entry.get_mut();
}{ // ... None falls through into... *rc -= 1;
self.data.insert(key.clone(), (DBValue::new(), -1)); },
Entry::Vacant(entry) => {
entry.insert((DBValue::new(), -1));
},
} }
} }
} }