use core::fmt;
use core::future::Future;
use core::ops::Bound;
use crate::commit::Commit;
use crate::nav::KvDirNav;
use crate::store::KvStore;
use crate::stream::KvStream;
#[derive(Clone, PartialEq, Eq)]
pub struct ScopedKvStore<KV> {
inner: KV,
dir: Vec<Vec<u8>>,
}
impl<KV> fmt::Debug for ScopedKvStore<KV> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("ScopedKvStore")
.field("dir_segments", &self.dir.len())
.finish()
}
}
impl<KV> ScopedKvStore<KV> {
pub fn new(inner: KV, dir: impl Into<Vec<Vec<u8>>>) -> Self {
Self {
inner,
dir: dir.into(),
}
}
pub fn dir(&self) -> &[Vec<u8>] {
&self.dir
}
pub fn inner(&self) -> &KV {
&self.inner
}
pub fn inner_mut(&mut self) -> &mut KV {
&mut self.inner
}
pub fn into_inner(self) -> KV {
self.inner
}
pub fn nested(self, seg: impl Into<Vec<u8>>) -> Self {
let seg = seg.into();
Self {
inner: self.inner,
dir: {
let mut dir = self.dir;
dir.push(seg);
dir
},
}
}
}
fn join_dir<'a>(pin: &'a [Vec<u8>], rel: &'a [&'a [u8]]) -> Vec<&'a [u8]> {
pin.iter()
.map(|s| s.as_slice())
.chain(rel.iter().copied())
.collect()
}
impl<KV: KvStore> KvStore for ScopedKvStore<KV> {
type Error = KV::Error;
async fn get(&self, dir: &[&[u8]], key: &[u8]) -> Result<Option<Vec<u8>>, Self::Error> {
self.inner.get(&join_dir(&self.dir, dir), key).await
}
async fn set(&mut self, dir: &[&[u8]], key: &[u8], value: &[u8]) -> Result<(), Self::Error> {
let d = join_dir(&self.dir, dir);
self.inner.set(&d, key, value).await
}
async fn delete(&mut self, dir: &[&[u8]], key: &[u8]) -> Result<(), Self::Error> {
let d = join_dir(&self.dir, dir);
self.inner.delete(&d, key).await
}
async fn exists(&self, dir: &[&[u8]], key: &[u8]) -> Result<bool, Self::Error> {
self.inner.exists(&join_dir(&self.dir, dir), key).await
}
fn range<'a>(
&'a self,
dir: &[&[u8]],
start: Bound<&'a [u8]>,
end: Bound<&'a [u8]>,
reverse: bool,
) -> KvStream<'a, Self::Error> {
let d = join_dir(&self.dir, dir);
self.inner.range(&d, start, end, reverse)
}
async fn clear_range(
&mut self,
dir: &[&[u8]],
start: Bound<&[u8]>,
end: Bound<&[u8]>,
) -> Result<(), Self::Error> {
let d = join_dir(&self.dir, dir);
self.inner.clear_range(&d, start, end).await
}
}
impl<KV: KvDirNav> KvDirNav for ScopedKvStore<KV> {
async fn list_dirs(&self, dir: &[&[u8]]) -> Result<Vec<Vec<u8>>, Self::Error> {
KvDirNav::list_dirs(&self.inner, &join_dir(&self.dir, dir)).await
}
async fn dir_exists(&self, dir: &[&[u8]]) -> Result<bool, Self::Error> {
KvDirNav::dir_exists(&self.inner, &join_dir(&self.dir, dir)).await
}
async fn remove_dir(&mut self, dir: &[&[u8]]) -> Result<bool, Self::Error> {
KvDirNav::remove_dir(&mut self.inner, &join_dir(&self.dir, dir)).await
}
}
impl<KV: Commit> Commit for ScopedKvStore<KV> {
type Error = KV::Error;
fn commit(self) -> impl Future<Output = Result<(), Self::Error>> {
self.inner.commit()
}
}