use crate::{FileHash, MetricElem}; use anyhow::Result; use bincode::config::standard; use redb::{Database, Durability, 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 { let db = Database::create(path)?; let txn = db.begin_write()?; txn.open_table(T_ENTRIES)?; txn.commit()?; Ok(Self { db }) } pub fn get(&self, type_name: &'static str, hash: FileHash) -> Result> { 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( &self, type_name: &'static str, hash: FileHash, value: &E, ) -> Result<()> { let mut txn = self.db.begin_write()?; txn.set_durability(Durability::Eventual); 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(()) } }