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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
#![feature(async_await)]
use parking_lot::RwLock;
use std::collections::HashMap;
use std::io;
use std::sync::Arc;
#[derive(Debug, Clone)]
pub struct Memdb {
hashmap: Arc<RwLock<HashMap<Vec<u8>, Vec<u8>>>>,
}
impl Memdb {
#[inline]
pub async fn open() -> io::Result<Self> {
Ok(Self {
hashmap: Arc::new(RwLock::new(HashMap::<Vec<u8>, Vec<u8>>::new())),
})
}
#[inline]
pub async fn set(
&mut self,
key: impl AsRef<[u8]>,
value: impl AsRef<[u8]>,
) -> io::Result<Option<Vec<u8>>> {
let hashmap = self.hashmap.clone();
let mut hashmap = hashmap.write();
Ok(hashmap.insert(key.as_ref().to_owned(), value.as_ref().to_owned()))
}
#[must_use]
#[inline]
pub async fn get(&self, key: impl AsRef<[u8]>) -> io::Result<Option<Vec<u8>>> {
let key = key.as_ref().to_owned();
let hashmap = &self.hashmap.read();
Ok(hashmap.get(&key).cloned())
}
#[inline]
pub async fn del(&mut self, key: impl AsRef<[u8]>) -> io::Result<Option<Vec<u8>>> {
let key = key.as_ref().to_owned();
let hashmap = &mut self.hashmap.write();
Ok(hashmap.remove(&key))
}
}