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>>), } impl ResourceStore { pub fn new_persistent(path: &Path) -> Result { Ok(Self::Redb(Database::create(path)?)) } pub fn new_memory() -> Self { Self::Memory(HashMap::new().into()) } pub fn get(&self, key: Resource) -> Result>> { 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 { 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 sha256(x: &[u8]) -> [u8; 32] { let mut hasher = Sha256::new(); hasher.update(x); hasher.finalize().into() }