summaryrefslogtreecommitdiff
path: root/shared/src/store.rs
blob: 37e3ab18fb2faa9c33258346dd59cc95c4561517 (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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
/*
    wearechat - generic multiplayer game with voip
    Copyright (C) 2025 metamuffin

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU Affero General Public License as published by
    the Free Software Foundation, version 3 of the License only.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU Affero General Public License for more details.

    You should have received a copy of the GNU Affero General Public License
    along with this program.  If not, see <https://www.gnu.org/licenses/>.
*/
use crate::{helper::ReadWrite, packets::Resource};
use anyhow::Result;
use redb::{Database, TableDefinition};
use sha2::{Digest, Sha256};
use std::{collections::HashMap, marker::PhantomData, 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> {
        let db = Database::create(path)?;
        let txn = db.begin_write()?;
        txn.open_table(T_ENTRIES)?;
        txn.commit()?;
        Ok(Self::Redb(db))
    }
    pub fn new_memory() -> Self {
        Self::Memory(HashMap::new().into())
    }
    pub fn get<T: ReadWrite>(&self, key: Resource<T>) -> Result<Option<T>> {
        self.get_raw(Resource(key.0, PhantomData))?
            .map(|b| T::read(&mut b.as_slice()))
            .transpose()
    }
    pub fn set<T: ReadWrite>(&self, value: &T) -> Result<Resource<T>> {
        Ok(Resource(self.set_raw(&value.write_alloc())?.0, PhantomData))
    }
    pub fn get_raw(&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_raw(&self, value: &[u8]) -> Result<Resource> {
        let key = Resource(sha256(value), PhantomData);
        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()
}