65 lines
1.4 KiB
Rust
65 lines
1.4 KiB
Rust
use core::slice::SlicePattern;
|
|
|
|
use std::path::{Path};
|
|
use std::sync::Arc;
|
|
|
|
use async_trait::async_trait;
|
|
|
|
#[derive(Clone)]
|
|
pub struct Db(Arc<dyn DbTrait + Send + Sync + 'static>);
|
|
|
|
impl Db {
|
|
pub fn new_sled(path: &Path) -> Self {
|
|
Self(Arc::new(DefaultDb::new(path)))
|
|
}
|
|
}
|
|
|
|
impl std::ops::Deref for Db {
|
|
type Target = Arc<dyn DbTrait + Send + Sync + 'static>;
|
|
|
|
fn deref(&self) -> &Self::Target {
|
|
&self.0
|
|
}
|
|
}
|
|
|
|
struct DefaultDb {
|
|
db: sled::Db,
|
|
}
|
|
|
|
impl DefaultDb {
|
|
pub fn new(path: &Path) -> Self {
|
|
Self {
|
|
db: sled::open(path).expect("to be able open a sled path"),
|
|
}
|
|
}
|
|
}
|
|
|
|
#[async_trait]
|
|
pub trait DbTrait {
|
|
async fn insert(&self, namespace: &str, key: &str, value: &[u8]) -> anyhow::Result<()>;
|
|
async fn get_all(&self, namespace: &str) -> anyhow::Result<Vec<Vec<u8>>>;
|
|
}
|
|
|
|
#[async_trait]
|
|
impl DbTrait for DefaultDb {
|
|
async fn insert(&self, namespace: &str, key: &str, value: &[u8]) -> anyhow::Result<()> {
|
|
let tree = self.db.open_tree(namespace)?;
|
|
|
|
tree.insert(key, value)?;
|
|
|
|
//tree.flush_async().await?;
|
|
|
|
Ok(())
|
|
}
|
|
|
|
async fn get_all(&self, namespace: &str) -> anyhow::Result<Vec<Vec<u8>>> {
|
|
let tree = self.db.open_tree(namespace)?;
|
|
|
|
Ok(tree
|
|
.iter()
|
|
.flatten()
|
|
.map(|(_, val)| val.as_slice().to_vec())
|
|
.collect::<Vec<_>>())
|
|
}
|
|
}
|