openethereum/util/src/memorydb.rs

255 lines
6.5 KiB
Rust
Raw Normal View History

2016-02-05 13:40:41 +01:00
// Copyright 2015, 2016 Ethcore (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Parity is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Parity. If not, see <http://www.gnu.org/licenses/>.
2016-04-06 10:07:24 +02:00
//! Reference-counted memory-based `HashDB` implementation.
2015-11-28 00:14:40 +01:00
use hash::*;
use bytes::*;
use rlp::*;
2015-11-28 00:14:40 +01:00
use sha3::*;
use hashdb::*;
use heapsize::*;
use std::mem;
2015-11-28 00:14:40 +01:00
use std::collections::HashMap;
2016-03-11 10:57:58 +01:00
use std::default::Default;
2015-11-28 00:14:40 +01:00
#[derive(Debug,Clone)]
2016-04-06 10:07:24 +02:00
/// Reference-counted memory-based `HashDB` implementation.
2015-11-28 01:38:36 +01:00
///
/// Use `new()` to create a new database. Insert items with `insert()`, remove items
/// with `remove()`, check for existence with `containce()` and lookup a hash to derive
/// the data with `get()`. Clear with `clear()` and purge the portions of the data
2015-11-28 01:38:36 +01:00
/// that have no references with `purge()`.
2016-03-11 10:57:58 +01:00
///
2015-11-28 01:38:36 +01:00
/// # Example
/// ```rust
/// extern crate ethcore_util;
/// use ethcore_util::hashdb::*;
/// use ethcore_util::memorydb::*;
/// fn main() {
/// let mut m = MemoryDB::new();
/// let d = "Hello world!".as_bytes();
///
/// let k = m.insert(d);
/// assert!(m.contains(&k));
/// assert_eq!(m.get(&k).unwrap(), d);
2015-11-28 01:38:36 +01:00
///
/// m.insert(d);
/// assert!(m.contains(&k));
2015-11-28 01:38:36 +01:00
///
/// m.remove(&k);
/// assert!(m.contains(&k));
2015-11-28 01:38:36 +01:00
///
/// m.remove(&k);
/// assert!(!m.contains(&k));
2015-11-28 01:38:36 +01:00
///
/// m.remove(&k);
/// assert!(!m.contains(&k));
2015-11-30 02:57:02 +01:00
///
/// m.insert(d);
/// assert!(!m.contains(&k));
2015-11-30 02:57:02 +01:00
2015-11-28 01:38:36 +01:00
/// m.insert(d);
/// assert!(m.contains(&k));
/// assert_eq!(m.get(&k).unwrap(), d);
2015-11-28 01:38:36 +01:00
///
/// m.remove(&k);
/// assert!(!m.contains(&k));
2015-11-28 01:38:36 +01:00
/// }
/// ```
#[derive(PartialEq)]
2015-11-28 00:14:40 +01:00
pub struct MemoryDB {
data: HashMap<H256, (Bytes, i32)>,
static_null_rlp: (Bytes, i32),
2015-11-28 00:14:40 +01:00
}
2016-03-11 10:57:58 +01:00
impl Default for MemoryDB {
fn default() -> Self {
MemoryDB::new()
}
}
2015-11-28 00:14:40 +01:00
impl MemoryDB {
2015-11-28 01:12:59 +01:00
/// Create a new instance of the memory DB.
2015-11-28 00:14:40 +01:00
pub fn new() -> MemoryDB {
MemoryDB {
data: HashMap::new(),
static_null_rlp: (vec![0x80u8; 1], 1),
2015-11-28 00:14:40 +01:00
}
}
2015-11-28 01:12:59 +01:00
/// Clear all data from the database.
///
/// # Examples
/// ```rust
/// extern crate ethcore_util;
/// use ethcore_util::hashdb::*;
/// use ethcore_util::memorydb::*;
/// fn main() {
/// let mut m = MemoryDB::new();
/// let hello_bytes = "Hello world!".as_bytes();
/// let hash = m.insert(hello_bytes);
/// assert!(m.contains(&hash));
2015-11-28 01:12:59 +01:00
/// m.clear();
/// assert!(!m.contains(&hash));
2015-11-28 01:12:59 +01:00
/// }
/// ```
2015-11-28 00:14:40 +01:00
pub fn clear(&mut self) {
self.data.clear();
}
2015-11-28 01:12:59 +01:00
/// Purge all zero-referenced data from the database.
2015-11-28 00:14:40 +01:00
pub fn purge(&mut self) {
2015-11-28 01:12:59 +01:00
let empties: Vec<_> = self.data.iter()
.filter(|&(_, &(_, rc))| rc == 0)
.map(|(k, _)| k.clone())
.collect();
2015-11-28 00:14:40 +01:00
for empty in empties { self.data.remove(&empty); }
}
2015-11-28 03:08:57 +01:00
/// Grab the raw information associated with a key. Returns None if the key
2015-11-28 03:08:57 +01:00
/// doesn't exist.
///
/// Even when Some is returned, the data is only guaranteed to be useful
/// when the refs > 0.
pub fn raw(&self, key: &H256) -> Option<&(Bytes, i32)> {
if key == &SHA3_NULL_RLP {
return Some(&self.static_null_rlp);
}
self.data.get(key)
2015-11-28 03:08:57 +01:00
}
/// Return the internal map of hashes to data, clearing the current state.
pub fn drain(&mut self) -> HashMap<H256, (Bytes, i32)> {
let mut data = HashMap::new();
mem::swap(&mut self.data, &mut data);
data
2015-11-28 03:08:57 +01:00
}
2015-11-29 15:50:33 +01:00
/// Denote than an existing value has the given key. Used when a key gets removed without
/// a prior insert and thus has a negative reference with no value.
2016-03-11 10:57:58 +01:00
///
/// May safely be called even if the key's value is known, in which case it will be a no-op.
2015-11-29 15:50:33 +01:00
pub fn denote(&self, key: &H256, value: Bytes) -> &(Bytes, i32) {
if self.raw(key) == None {
2015-11-29 15:50:33 +01:00
unsafe {
2015-11-29 16:00:23 +01:00
let p = &self.data as *const HashMap<H256, (Bytes, i32)> as *mut HashMap<H256, (Bytes, i32)>;
(*p).insert(key.clone(), (value, 0));
2015-11-29 15:50:33 +01:00
}
}
self.raw(key).unwrap()
2015-11-29 15:50:33 +01:00
}
/// Returns the size of allocated heap memory
pub fn mem_used(&self) -> usize {
self.data.heap_size_of_children()
}
2015-11-28 00:14:40 +01:00
}
static NULL_RLP_STATIC: [u8; 1] = [0x80; 1];
2015-11-28 00:14:40 +01:00
impl HashDB for MemoryDB {
2015-11-29 15:50:33 +01:00
fn lookup(&self, key: &H256) -> Option<&[u8]> {
if key == &SHA3_NULL_RLP {
return Some(&NULL_RLP_STATIC);
}
2015-11-28 00:14:40 +01:00
match self.data.get(key) {
2015-11-29 15:50:33 +01:00
Some(&(ref d, rc)) if rc > 0 => Some(d),
2015-11-28 00:14:40 +01:00
_ => None
}
}
2015-12-04 18:05:59 +01:00
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()
}
2015-11-28 00:14:40 +01:00
fn exists(&self, key: &H256) -> bool {
if key == &SHA3_NULL_RLP {
return true;
}
2015-11-28 00:14:40 +01:00
match self.data.get(key) {
Some(&(_, x)) if x > 0 => true,
_ => false
}
}
fn insert(&mut self, value: &[u8]) -> H256 {
if value == &NULL_RLP {
return SHA3_NULL_RLP.clone();
}
2015-11-28 00:14:40 +01:00
let key = value.sha3();
if match self.data.get_mut(&key) {
2015-11-30 02:57:02 +01:00
Some(&mut (ref mut old_value, ref mut rc @ -0x80000000i32 ... 0)) => {
2015-11-28 01:38:36 +01:00
*old_value = From::from(value.bytes());
2015-11-30 02:57:02 +01:00
*rc += 1;
2015-11-28 01:38:36 +01:00
false
},
2015-11-28 00:14:40 +01:00
Some(&mut (_, ref mut x)) => { *x += 1; false } ,
None => true,
}{ // ... None falls through into...
2015-11-28 01:38:36 +01:00
self.data.insert(key.clone(), (From::from(value.bytes()), 1));
2015-11-28 00:14:40 +01:00
}
key
}
2015-11-28 03:08:57 +01:00
2015-11-30 02:57:02 +01:00
fn emplace(&mut self, key: H256, value: Bytes) {
if value == &NULL_RLP {
return;
}
2015-11-30 02:57:02 +01:00
match self.data.get_mut(&key) {
Some(&mut (ref mut old_value, ref mut rc @ -0x80000000i32 ... 0)) => {
*old_value = value;
*rc += 1;
return;
},
Some(&mut (_, ref mut x)) => { *x += 1; return; } ,
None => {},
}
// ... None falls through into...
self.data.insert(key, (value, 1));
}
2015-11-28 00:14:40 +01:00
fn kill(&mut self, key: &H256) {
if key == &SHA3_NULL_RLP {
return;
}
2015-11-28 00:14:40 +01:00
if match self.data.get_mut(key) {
Some(&mut (_, ref mut x)) => { *x -= 1; false }
None => true
}{ // ... None falls through into...
2015-11-28 01:38:36 +01:00
self.data.insert(key.clone(), (Bytes::new(), -1));
2015-11-28 00:14:40 +01:00
}
}
}
2015-11-29 15:50:33 +01:00
#[test]
fn memorydb_denote() {
let mut m = MemoryDB::new();
let hello_bytes = b"Hello world!";
let hash = m.insert(hello_bytes);
assert_eq!(m.get(&hash).unwrap(), b"Hello world!");
2015-11-29 15:50:33 +01:00
2015-11-29 16:00:23 +01:00
for _ in 0..1000 {
2015-11-29 15:50:33 +01:00
let r = H256::random();
let k = r.sha3();
let &(ref v, ref rc) = m.denote(&k, r.bytes().to_vec());
assert_eq!(v, &r.bytes());
assert_eq!(*rc, 0);
}
assert_eq!(m.get(&hash).unwrap(), b"Hello world!");
2015-12-01 16:39:44 +01:00
}