blob: 44e5e3dced311d42e2f8b6eb590286a04911da94 (
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
|
use crate::packets::Resource;
use anyhow::Result;
use redb::{Database, TableDefinition};
use sha2::{Digest, Sha256};
use std::path::Path;
const T_ENTRIES: TableDefinition<[u8; 32], &[u8]> = TableDefinition::new("e");
pub struct ResourceStore {
db: Database,
}
impl ResourceStore {
pub fn new(path: &Path) -> Result<Self> {
Ok(Self {
db: Database::create(path)?,
})
}
pub fn get(&self, key: Resource) -> Result<Option<Vec<u8>>> {
let txn = self.db.begin_read()?;
let ent = txn.open_table(T_ENTRIES)?;
match ent.get(key.0)? {
Some(x) => Ok(Some(x.value().to_vec())),
None => Ok(None),
}
}
pub fn set(&self, value: &[u8]) -> Result<()> {
let key = sha256(value);
let txn = self.db.begin_write()?;
let mut ent = txn.open_table(T_ENTRIES)?;
ent.insert(key, value)?;
drop(ent);
txn.commit()?;
Ok(())
}
}
pub fn sha256(x: &[u8]) -> [u8; 32] {
let mut hasher = Sha256::new();
hasher.update(x);
hasher.finalize().into()
}
|