aboutsummaryrefslogtreecommitdiff
path: root/src/cache.rs
blob: 6767f7924910a03c53d186f67414e4760a688e07 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
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<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 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(())
    }
}