lighthouse/beacon_node/store/src/memory_store.rs

68 lines
1.9 KiB
Rust
Raw Normal View History

2019-05-21 08:49:24 +00:00
use super::{Error, Store};
use parking_lot::RwLock;
use std::collections::HashMap;
2019-06-08 13:46:04 +00:00
use std::sync::Arc;
type DBHashMap = HashMap<Vec<u8>, Vec<u8>>;
2019-05-21 08:49:24 +00:00
/// A thread-safe `HashMap` wrapper.
2019-06-08 13:46:04 +00:00
#[derive(Clone)]
2019-05-21 08:20:23 +00:00
pub struct MemoryStore {
2019-06-08 13:46:04 +00:00
// Note: this `Arc` is only included because of an artificial constraint by gRPC. Hopefully we
// can remove this one day.
db: Arc<RwLock<DBHashMap>>,
}
2019-05-21 08:20:23 +00:00
impl MemoryStore {
2019-05-21 08:49:24 +00:00
/// Create a new, empty database.
pub fn open() -> Self {
Self {
2019-06-08 13:46:04 +00:00
db: Arc::new(RwLock::new(HashMap::new())),
}
}
fn get_key_for_col(col: &str, key: &[u8]) -> Vec<u8> {
let mut col = col.as_bytes().to_vec();
col.append(&mut key.to_vec());
col
}
}
2019-05-21 08:20:23 +00:00
impl Store for MemoryStore {
/// Get the value of some key from the database. Returns `None` if the key does not exist.
2019-05-21 08:49:24 +00:00
fn get_bytes(&self, col: &str, key: &[u8]) -> Result<Option<Vec<u8>>, Error> {
2019-05-21 08:20:23 +00:00
let column_key = MemoryStore::get_key_for_col(col, key);
Ok(self
.db
.read()
.get(&column_key)
.and_then(|val| Some(val.clone())))
}
/// Puts a key in the database.
fn put_bytes(&self, col: &str, key: &[u8], val: &[u8]) -> Result<(), Error> {
2019-05-21 08:20:23 +00:00
let column_key = MemoryStore::get_key_for_col(col, key);
self.db.write().insert(column_key, val.to_vec());
Ok(())
}
/// Return true if some key exists in some column.
fn key_exists(&self, col: &str, key: &[u8]) -> Result<bool, Error> {
2019-05-21 08:20:23 +00:00
let column_key = MemoryStore::get_key_for_col(col, key);
Ok(self.db.read().contains_key(&column_key))
}
/// Delete some key from the database.
fn key_delete(&self, col: &str, key: &[u8]) -> Result<(), Error> {
2019-05-21 08:20:23 +00:00
let column_key = MemoryStore::get_key_for_col(col, key);
self.db.write().remove(&column_key);
Ok(())
}
}