1#![feature(async_await)]
2
3use parking_lot::RwLock;
21
22use std::collections::HashMap;
23use std::io;
24use std::sync::Arc;
25
26#[derive(Debug, Clone)]
28pub struct Memdb {
29 hashmap: Arc<RwLock<HashMap<Vec<u8>, Vec<u8>>>>,
30}
31
32impl Memdb {
33 #[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 #[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 #[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 #[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}