aboutsummaryrefslogtreecommitdiff
path: root/database/src/backends/rocksdb.rs
blob: f4ed55b61dae73eb6478d45f01b7287fea0f5cf7 (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
/*
    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 std::path::Path;

use crate::backends::KV;
use anyhow::Result;
use rocksdb::DB;

pub struct Rocksdb {
    db: DB,
}

impl Rocksdb {
    pub fn new(path: &Path) -> Result<Self> {
        Ok(Self {
            db: DB::open_default(path)?,
        })
    }
}
impl KV for Rocksdb {
    fn set(&self, key: &[u8], value: &[u8]) -> Result<()> {
        Ok(self.db.put(key, value)?)
    }
    fn get<'a>(&'a self, key: &[u8]) -> Result<Option<Vec<u8>>> {
        Ok(self.db.get(key)?)
    }
    fn del(&self, key: &[u8]) -> Result<()> {
        Ok(self.db.delete(key)?)
    }
    fn next(&self, key: &[u8]) -> Result<Option<Vec<u8>>> {
        let mut it = self.db.raw_iterator();
        it.seek_for_prev(key);
        it.next();
        Ok(it.key().map(Vec::from))
    }
    fn prev(&self, key: &[u8]) -> Result<Option<Vec<u8>>> {
        let mut it = self.db.raw_iterator();
        it.seek(key);
        it.prev();
        Ok(it.key().map(Vec::from))
    }
}