From 2a17ceac1ab5cdee98d20a928795a1aba06c8be7 Mon Sep 17 00:00:00 2001 From: metamuffin Date: Wed, 27 Nov 2024 22:34:03 +0000 Subject: Replace sled with redb (Also replaces serde to bincode.) (#2) Reviewed-on: https://codeberg.org/lialenck/embeddings-sort/pulls/2 Co-authored-by: metamuffin Co-committed-by: metamuffin --- src/cache.rs | 45 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 45 insertions(+) create mode 100644 src/cache.rs (limited to 'src/cache.rs') 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 { + 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 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(()) + } +} -- cgit v1.2.3-70-g09d2