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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
|
use crate::packets::Resource;
use anyhow::Result;
use redb::{Database, TableDefinition};
use sha2::{Digest, Sha256};
use std::{collections::HashMap, path::Path, sync::Mutex};
const T_ENTRIES: TableDefinition<[u8; 32], &[u8]> = TableDefinition::new("e");
pub enum ResourceStore {
Redb(Database),
Memory(Mutex<HashMap<Resource, Vec<u8>>>),
}
impl ResourceStore {
pub fn new_persistent(path: &Path) -> Result<Self> {
Ok(Self::Redb(Database::create(path)?))
}
pub fn new_memory() -> Self {
Self::Memory(HashMap::new().into())
}
pub fn get(&self, key: Resource) -> Result<Option<Vec<u8>>> {
match self {
ResourceStore::Redb(database) => {
let txn = database.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),
}
}
ResourceStore::Memory(map) => Ok(map.lock().unwrap().get(&key).map(|x| x.to_vec())),
}
}
pub fn set(&self, value: &[u8]) -> Result<Resource> {
let key = Resource(sha256(value));
match self {
ResourceStore::Redb(database) => {
let txn = database.begin_write()?;
let mut ent = txn.open_table(T_ENTRIES)?;
ent.insert(key.0, value)?;
drop(ent);
txn.commit()?;
}
ResourceStore::Memory(map) => {
map.lock().unwrap().insert(key, value.to_vec());
}
}
Ok(key)
}
pub fn iter(&self, mut cb: impl FnMut(&[u8])) -> Result<()> {
match self {
ResourceStore::Redb(_database) => todo!(),
ResourceStore::Memory(mutex) => {
mutex.lock().unwrap().values().for_each(|v| cb(v));
Ok(())
}
}
}
}
pub fn sha256(x: &[u8]) -> [u8; 32] {
let mut hasher = Sha256::new();
hasher.update(x);
hasher.finalize().into()
}
|