From 02d65e6b7ce7a0e6bae054bd321c68dda1cb0de3 Mon Sep 17 00:00:00 2001 From: metamuffin Date: Tue, 7 Jan 2025 22:56:34 +0100 Subject: static typing for resources --- shared/src/store.rs | 18 +++++++++++++----- 1 file changed, 13 insertions(+), 5 deletions(-) (limited to 'shared/src/store.rs') diff --git a/shared/src/store.rs b/shared/src/store.rs index 38402fc..f63ed6c 100644 --- a/shared/src/store.rs +++ b/shared/src/store.rs @@ -14,11 +14,11 @@ You should have received a copy of the GNU Affero General Public License along with this program. If not, see . */ -use crate::packets::Resource; +use crate::packets::{ReadWrite, Resource}; use anyhow::Result; use redb::{Database, TableDefinition}; use sha2::{Digest, Sha256}; -use std::{collections::HashMap, path::Path, sync::Mutex}; +use std::{collections::HashMap, marker::PhantomData, path::Path, sync::Mutex}; const T_ENTRIES: TableDefinition<[u8; 32], &[u8]> = TableDefinition::new("e"); @@ -33,7 +33,15 @@ impl ResourceStore { pub fn new_memory() -> Self { Self::Memory(HashMap::new().into()) } - pub fn get(&self, key: Resource) -> Result>> { + pub fn get(&self, key: Resource) -> Result> { + self.get_raw(Resource(key.0, PhantomData))? + .map(|b| T::read(&mut b.as_slice())) + .transpose() + } + pub fn set(&self, value: &T) -> Result> { + Ok(Resource(self.set_raw(&value.write_alloc())?.0, PhantomData)) + } + pub fn get_raw(&self, key: Resource) -> Result>> { match self { ResourceStore::Redb(database) => { let txn = database.begin_read()?; @@ -46,8 +54,8 @@ impl ResourceStore { 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)); + pub fn set_raw(&self, value: &[u8]) -> Result { + let key = Resource(sha256(value), PhantomData); match self { ResourceStore::Redb(database) => { let txn = database.begin_write()?; -- cgit v1.2.3-70-g09d2