blob: 2f19ce6f593308487478da72074aca463f7313f3 (
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
|
/*
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::KV;
use anyhow::Result;
use std::{collections::BTreeMap, sync::RwLock};
pub struct Memory(RwLock<BTreeMap<Vec<u8>, Vec<u8>>>);
impl Memory {
pub fn new() -> Self {
Self(RwLock::new(BTreeMap::new()))
}
}
impl KV for Memory {
fn set(&self, key: &[u8], value: &[u8]) -> Result<()> {
self.0.write().unwrap().insert(key.to_vec(), value.to_vec());
Ok(())
}
fn get<'a>(&'a self, key: &[u8]) -> Result<Option<Vec<u8>>> {
Ok(self.0.read().unwrap().get(key).cloned())
}
fn del(&self, key: &[u8]) -> Result<()> {
self.0.write().unwrap().remove(key);
Ok(())
}
fn next(&self, key: &[u8]) -> Result<Option<Vec<u8>>> {
let r = self.0.read().unwrap();
Ok(r.range(key.to_vec()..).next().map(|(k, _)| k.to_owned()))
}
fn prev(&self, key: &[u8]) -> Result<Option<Vec<u8>>> {
let r = self.0.read().unwrap();
Ok(r.range(..key.to_vec())
.next_back()
.map(|(k, _)| k.to_owned()))
}
}
|