1use crate::{AsBytes, BitsyResult, Bytes, Key};
2use async_std::sync::{Arc, Mutex};
3use async_trait::async_trait;
4use std::collections::HashMap;
5
6pub trait DatabaseKey:
7 Key + AsBytes + std::cmp::Eq + std::hash::Hash + Send + Sync
8{
9}
10
11#[async_trait]
12pub trait Database {
13 async fn set_key(&mut self, k: impl DatabaseKey, v: Bytes) -> BitsyResult<()>;
14 async fn get_key(&self, k: impl DatabaseKey) -> BitsyResult<Option<Bytes>>;
15 async fn set_bytes(&self, b: Bytes, v: Bytes) -> BitsyResult<()>;
16 async fn get_bytes(&self, k: &Bytes) -> BitsyResult<Option<Bytes>>;
17}
18
19enum DbType {
20 InMemory,
21 #[allow(unused)]
22 Redis,
23}
24
25pub struct InMemory {
26 #[allow(unused)]
27 db_type: DbType,
28 items: Arc<Mutex<HashMap<Bytes, Bytes>>>,
29}
30
31impl InMemory {
32 pub fn new() -> Self {
33 Self {
34 db_type: DbType::InMemory,
35 items: Arc::new(Mutex::new(HashMap::default())),
36 }
37 }
38}
39
40impl Default for InMemory {
41 fn default() -> Self {
42 Self::new()
43 }
44}
45
46#[async_trait]
47impl Database for InMemory {
48 async fn set_key(&mut self, k: impl DatabaseKey, v: Bytes) -> BitsyResult<()> {
49 self.items.lock().await.insert(k.flatten(), v);
50 Ok(())
51 }
52
53 async fn get_key(&self, k: impl DatabaseKey) -> BitsyResult<Option<Bytes>> {
54 Ok(self.items.lock().await.remove(&k.flatten()))
55 }
56
57 async fn set_bytes(&self, k: Bytes, v: Bytes) -> BitsyResult<()> {
58 self.items.lock().await.insert(k, v);
59 Ok(())
60 }
61
62 async fn get_bytes(&self, k: &Bytes) -> BitsyResult<Option<Bytes>> {
63 Ok(self.items.lock().await.remove(k))
64 }
65}