aboutsummaryrefslogtreecommitdiff
path: root/database/src/backends/memory.rs
blob: 302b2326f42e6e9add7017084a1ef1485b2eccf1 (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
/*
    This file is part of jellything (https://codeberg.org/metamuffin/jellything)
    which is licensed under the GNU Affero General Public License (version 3); see /COPYING.
    Copyright (C) 2025 metamuffin <metamuffin.org>
*/

use crate::backends::{Db, ReadTransaction, ReadTxnFunction, WriteTransaction, WriteTxnFunction};
use anyhow::Result;
use std::{
    collections::BTreeMap,
    sync::{RwLock, RwLockReadGuard, RwLockWriteGuard},
};

type Inner = BTreeMap<Vec<u8>, Vec<u8>>;
pub struct Memory(RwLock<BTreeMap<Vec<u8>, Vec<u8>>>);

impl Memory {
    pub fn new() -> Self {
        Self(RwLock::new(BTreeMap::new()))
    }
}
impl Db for Memory {
    fn write_transaction(&self, f: &mut WriteTxnFunction) -> Result<()> {
        f(&mut self.0.write().unwrap())
    }
    fn read_transaction(&self, f: &mut ReadTxnFunction) -> Result<()> {
        f(&self.0.read().unwrap())
    }
}
impl WriteTransaction for RwLockWriteGuard<'_, Inner> {
    fn set(&mut self, key: &[u8], value: &[u8]) -> Result<()> {
        (**self).insert(key.to_vec(), value.to_vec());
        Ok(())
    }
    fn del(&mut self, key: &[u8]) -> Result<()> {
        (**self).remove(key);
        Ok(())
    }
}
impl ReadTransaction for RwLockWriteGuard<'_, Inner> {
    fn get(&self, key: &[u8]) -> Result<Option<Vec<u8>>> {
        Ok((**self).get(key).cloned())
    }
    fn iter<'a>(
        &'a self,
        key: &[u8],
        reverse: bool,
    ) -> Result<Box<dyn Iterator<Item = Result<Vec<u8>>> + 'a>> {
        Ok(if reverse {
            Box::new(self.range(key.to_vec()..).map(|e| Ok(e.0.to_vec())))
        } else {
            Box::new(self.range(..=key.to_vec()).rev().map(|e| Ok(e.0.to_vec())))
        })
    }
}
impl ReadTransaction for RwLockReadGuard<'_, Inner> {
    fn get(&self, key: &[u8]) -> Result<Option<Vec<u8>>> {
        Ok((**self).get(key).cloned())
    }
    fn iter<'a>(
        &'a self,
        key: &[u8],
        reverse: bool,
    ) -> Result<Box<dyn Iterator<Item = Result<Vec<u8>>> + 'a>> {
        Ok(if reverse {
            Box::new(self.range(key.to_vec()..).map(|e| Ok(e.0.to_vec())))
        } else {
            Box::new(self.range(..=key.to_vec()).rev().map(|e| Ok(e.0.to_vec())))
        })
    }
}