Skip to content

Commit

Permalink
refactor: comment out homedb and have typeddb use arg prefixes
Browse files Browse the repository at this point in the history
  • Loading branch information
luketchang committed Oct 15, 2021
1 parent a240fac commit f242a39
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 36 deletions.
4 changes: 2 additions & 2 deletions rust/optics-core/src/db/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,8 @@ mod typed_db;
pub use typed_db::*;

/// DB operations tied to specific home
mod home_db;
pub use home_db::*;
// mod home_db;
// pub use home_db::*;

use crate::{Decode, Encode, OpticsError};

Expand Down
45 changes: 11 additions & 34 deletions rust/optics-core/src/db/typed_db.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,28 +6,23 @@ use color_eyre::Result;
///
/// Key structure: ```<type_prefix>_<additional_prefix(es)>_<key>```
#[derive(Debug, Clone)]
pub struct TypedDB {
db: DB,
type_prefix: Vec<u8>,
}
pub struct TypedDB(DB);


impl TypedDB {
/// Instantiate new `TypedDB`
pub fn new(db: DB, type_prefix: impl Into<Vec<u8>>) -> Self {
Self {
db,
type_prefix: type_prefix.into(),
}
pub fn new(db: DB) -> Self {
Self(db)
}

/// Return reference to raw db
pub fn db(&self) -> &DB {
&self.db
&self.0
}

fn full_prefix(&self, prefix: impl AsRef<[u8]>) -> Vec<u8> {
fn full_prefix(entity: impl AsRef<[u8]>, prefix: impl AsRef<[u8]>) -> Vec<u8> {
let mut full_prefix = vec![];
full_prefix.extend(self.type_prefix.as_ref() as &[u8]);
full_prefix.extend(entity.as_ref());
full_prefix.extend("_".as_bytes());
full_prefix.extend(prefix.as_ref());
full_prefix
Expand All @@ -36,39 +31,21 @@ impl TypedDB {
/// Store encodable value
pub fn store_encodable<V: Encode>(
&self,
entity: impl AsRef<[u8]>,
prefix: impl AsRef<[u8]>,
key: impl AsRef<[u8]>,
value: &V,
) -> Result<(), DbError> {
self.db
.store_encodable(&self.full_prefix(prefix), key, value)
self.0.store_encodable(TypedDB::full_prefix(entity, prefix), key, value)
}

/// Retrieve decodable value
pub fn retrieve_decodable<V: Decode>(
&self,
entity: impl AsRef<[u8]>,
prefix: impl AsRef<[u8]>,
key: impl AsRef<[u8]>,
) -> Result<Option<V>, DbError> {
self.db.retrieve_decodable(&self.full_prefix(prefix), key)
}

/// Store encodable kv pair
pub fn store_keyed_encodable<K: Encode, V: Encode>(
&self,
prefix: impl AsRef<[u8]>,
key: &K,
value: &V,
) -> Result<(), DbError> {
self.store_encodable(prefix, key.to_vec(), value)
}

/// Retrieve decodable value given encodable key
pub fn retrieve_keyed_decodable<K: Encode, V: Decode>(
&self,
prefix: impl AsRef<[u8]>,
key: &K,
) -> Result<Option<V>, DbError> {
self.retrieve_decodable(prefix, key.to_vec())
self.0.retrieve_decodable(TypedDB::full_prefix(entity, prefix), key)
}
}

0 comments on commit f242a39

Please sign in to comment.