1use dyn_clonable::*;
2
3#[clonable]
4pub trait DataStorage: Clone {
5 fn get(&self, key: &str) -> Result<Option<Vec<u8>>, String>;
6 fn insert(&self, key: &str, value: &[u8]) -> Result<(), String>;
7 fn open(path: &str) -> Self
8 where
9 Self: Sized;
10}
11
12#[derive(Clone)]
13pub struct SledDataStorage {
14 db: Option<sled::Db>,
15}
16
17impl DataStorage for SledDataStorage {
18 fn open(path: &str) -> Self {
19 match sled::open(path) {
20 Ok(db) => Self { db: Some(db) },
21 Err(_e) => Self { db: None },
22 }
23 }
24
25 fn get(&self, key: &str) -> Result<Option<Vec<u8>>, String> {
26 if let Some(ref db) = self.db {
27 match db.get(key.as_bytes()).unwrap() {
28 Some(value) => Ok(Some(value.to_vec())),
29 None => Ok(None),
30 }
31 } else {
32 Err("Data Storage must be opened first".to_string())
33 }
34 }
35
36 fn insert(&self, key: &str, value: &[u8]) -> Result<(), String> {
37 if let Some(ref db) = self.db {
38 match db.insert(key.as_bytes(), value) {
39 Ok(_) => Ok(()),
40 Err(e) => Err(e.to_string()),
41 }
42 } else {
43 Err("Data Storage must be opened first".to_string())
44 }
45 }
46}