aboutsummaryrefslogtreecommitdiff
path: root/src/cache.rs
diff options
context:
space:
mode:
Diffstat (limited to 'src/cache.rs')
-rw-r--r--src/cache.rs45
1 files changed, 45 insertions, 0 deletions
diff --git a/src/cache.rs b/src/cache.rs
new file mode 100644
index 0000000..608adb5
--- /dev/null
+++ b/src/cache.rs
@@ -0,0 +1,45 @@
+use crate::{FileHash, MetricElem};
+use anyhow::Result;
+use bincode::config::standard;
+use redb::{Database, TableDefinition};
+use std::path::Path;
+
+const T_ENTRIES: TableDefinition<(&str, FileHash), &[u8]> = TableDefinition::new("entries");
+
+pub struct Cache {
+ db: Database,
+}
+impl Cache {
+ pub fn open(path: &Path) -> Result<Self> {
+ let db = Database::create(path)?;
+ let txn = db.begin_write()?;
+ txn.open_table(T_ENTRIES)?;
+ txn.commit()?;
+ Ok(Self { db })
+ }
+ pub fn get<E: MetricElem>(&self, type_name: &'static str, hash: FileHash) -> Result<Option<E>> {
+ let txn = self.db.begin_read()?;
+ let table = txn.open_table(T_ENTRIES)?;
+ if let Some(e) = table.get((type_name, hash))? {
+ Ok(Some(bincode::decode_from_slice(e.value(), standard())?.0))
+ } else {
+ Ok(None)
+ }
+ }
+ pub fn insert<E: MetricElem>(
+ &self,
+ type_name: &'static str,
+ hash: FileHash,
+ value: &E,
+ ) -> Result<()> {
+ let txn = self.db.begin_write()?;
+ let mut table = txn.open_table(T_ENTRIES)?;
+ table.insert(
+ (type_name, hash),
+ bincode::encode_to_vec(value, standard())?.as_slice(),
+ )?;
+ drop(table);
+ txn.commit()?;
+ Ok(())
+ }
+}