kotoba_db_engine_memory/
lib.rs

1use kotoba_db_core::engine::StorageEngine;
2use std::collections::HashMap;
3use anyhow::Result;
4
5pub struct MemoryStorageEngine {
6    store: HashMap<Vec<u8>, Vec<u8>>,
7}
8
9impl MemoryStorageEngine {
10    /// Creates a new in-memory storage engine.
11    pub fn new() -> Self {
12        Self {
13            store: HashMap::new(),
14        }
15    }
16}
17
18#[async_trait::async_trait]
19impl StorageEngine for MemoryStorageEngine {
20    async fn put(&mut self, key: &[u8], value: &[u8]) -> Result<()> {
21        self.store.insert(key.to_vec(), value.to_vec());
22        Ok(())
23    }
24
25    async fn get(&self, key: &[u8]) -> Result<Option<Vec<u8>>> {
26        Ok(self.store.get(key).cloned())
27    }
28
29    async fn delete(&mut self, key: &[u8]) -> Result<()> {
30        self.store.remove(key);
31        Ok(())
32    }
33
34    async fn scan(&self, prefix: &[u8]) -> Result<Vec<(Vec<u8>, Vec<u8>)>> {
35        let mut results = Vec::new();
36        for (key, value) in &self.store {
37            if key.starts_with(prefix) {
38                results.push((key.clone(), value.clone()));
39            }
40        }
41        // Sort by key for consistent ordering
42        results.sort_by(|a, b| a.0.cmp(&b.0));
43        Ok(results)
44    }
45}
46
47impl Default for MemoryStorageEngine {
48    fn default() -> Self {
49        Self::new()
50    }
51}