memdb/
lib.rs

1#![feature(async_await)]
2
3//! Thread-safe in-memory key-value store. Ideal for development and prototyping.
4//! Does not persist to disk.
5//!
6//! ## Examples
7//!
8//! ```
9//! # #![feature(async_await)]
10//! # #[runtime::main]
11//! # async fn main() -> std::io::Result<()> {
12//! let mut db = memdb::Memdb::open().await?;
13//! db.set("beep", "boop").await?;
14//! let val = db.get("beep").await?;
15//! assert_eq!(val, Some("boop".as_bytes().to_owned()));
16//! # Ok(())
17//! # }
18//! ```
19
20use parking_lot::RwLock;
21
22use std::collections::HashMap;
23use std::io;
24use std::sync::Arc;
25
26/// Key-value database.
27#[derive(Debug, Clone)]
28pub struct Memdb {
29    hashmap: Arc<RwLock<HashMap<Vec<u8>, Vec<u8>>>>,
30}
31
32impl Memdb {
33    /// Create a new instance.
34    #[inline]
35    pub async fn open() -> io::Result<Self> {
36        Ok(Self {
37            hashmap: Arc::new(RwLock::new(HashMap::<Vec<u8>, Vec<u8>>::new())),
38        })
39    }
40
41    /// Set a value in the database.
42    #[inline]
43    pub async fn set(
44        &mut self,
45        key: impl AsRef<[u8]>,
46        value: impl AsRef<[u8]>,
47    ) -> io::Result<Option<Vec<u8>>> {
48        let hashmap = self.hashmap.clone();
49        let mut hashmap = hashmap.write();
50        Ok(hashmap.insert(key.as_ref().to_owned(), value.as_ref().to_owned()))
51    }
52
53    /// Get a value from the database.
54    #[must_use]
55    #[inline]
56    pub async fn get(&self, key: impl AsRef<[u8]>) -> io::Result<Option<Vec<u8>>> {
57        let key = key.as_ref().to_owned();
58        let hashmap = &self.hashmap.read();
59        Ok(hashmap.get(&key).cloned())
60    }
61
62    /// Delete a value from the database.
63    #[inline]
64    pub async fn del(&mut self, key: impl AsRef<[u8]>) -> io::Result<Option<Vec<u8>>> {
65        let key = key.as_ref().to_owned();
66        let hashmap = &mut self.hashmap.write();
67        Ok(hashmap.remove(&key))
68    }
69}