2019-05-20 08:01:51 +00:00
|
|
|
use super::{DBValue, Error, Store};
|
|
|
|
use parking_lot::RwLock;
|
|
|
|
use std::collections::HashMap;
|
2019-02-14 01:09:18 +00:00
|
|
|
|
|
|
|
type DBHashMap = HashMap<Vec<u8>, Vec<u8>>;
|
|
|
|
|
|
|
|
pub struct MemoryDB {
|
|
|
|
db: RwLock<DBHashMap>,
|
|
|
|
}
|
|
|
|
|
|
|
|
impl MemoryDB {
|
|
|
|
pub fn open() -> Self {
|
|
|
|
Self {
|
2019-05-20 08:01:51 +00:00
|
|
|
db: RwLock::new(HashMap::new()),
|
2019-02-14 01:09:18 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
fn get_key_for_col(col: &str, key: &[u8]) -> Vec<u8> {
|
2019-05-20 08:01:51 +00:00
|
|
|
let mut col = col.as_bytes().to_vec();
|
|
|
|
col.append(&mut key.to_vec());
|
|
|
|
col
|
2019-02-14 01:09:18 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-05-20 08:01:51 +00:00
|
|
|
impl Store for MemoryDB {
|
2019-02-14 01:09:18 +00:00
|
|
|
/// Get the value of some key from the database. Returns `None` if the key does not exist.
|
2019-05-20 08:01:51 +00:00
|
|
|
fn get_bytes(&self, col: &str, key: &[u8]) -> Result<Option<DBValue>, Error> {
|
|
|
|
let column_key = MemoryDB::get_key_for_col(col, key);
|
2019-02-14 01:09:18 +00:00
|
|
|
|
2019-05-20 08:01:51 +00:00
|
|
|
Ok(self
|
|
|
|
.db
|
|
|
|
.read()
|
|
|
|
.get(&column_key)
|
|
|
|
.and_then(|val| Some(val.clone())))
|
2019-02-14 01:09:18 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
/// Puts a key in the database.
|
2019-05-20 08:01:51 +00:00
|
|
|
fn put_bytes(&self, col: &str, key: &[u8], val: &[u8]) -> Result<(), Error> {
|
|
|
|
let column_key = MemoryDB::get_key_for_col(col, key);
|
2019-02-14 01:09:18 +00:00
|
|
|
|
2019-05-20 08:01:51 +00:00
|
|
|
self.db.write().insert(column_key, val.to_vec());
|
|
|
|
|
|
|
|
Ok(())
|
2019-02-14 01:09:18 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
/// Return true if some key exists in some column.
|
2019-05-20 08:01:51 +00:00
|
|
|
fn key_exists(&self, col: &str, key: &[u8]) -> Result<bool, Error> {
|
|
|
|
let column_key = MemoryDB::get_key_for_col(col, key);
|
2019-02-14 01:09:18 +00:00
|
|
|
|
2019-05-20 08:01:51 +00:00
|
|
|
Ok(self.db.read().contains_key(&column_key))
|
2019-02-14 01:09:18 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
/// Delete some key from the database.
|
2019-05-20 08:01:51 +00:00
|
|
|
fn key_delete(&self, col: &str, key: &[u8]) -> Result<(), Error> {
|
|
|
|
let column_key = MemoryDB::get_key_for_col(col, key);
|
2019-02-14 01:09:18 +00:00
|
|
|
|
2019-05-20 08:01:51 +00:00
|
|
|
self.db.write().remove(&column_key);
|
2019-02-14 01:09:18 +00:00
|
|
|
|
2019-05-20 08:01:51 +00:00
|
|
|
Ok(())
|
2019-02-14 01:09:18 +00:00
|
|
|
}
|
|
|
|
}
|