bonsaidb_core/keyvalue/implementation/
namespaced.rs

1use async_trait::async_trait;
2
3use super::{KeyOperation, KeyValue, Output};
4use crate::keyvalue::AsyncKeyValue;
5use crate::Error;
6
7/// A namespaced key-value store. All operations performed with this will be
8/// separate from other namespaces.
9pub struct Namespaced<'a, K> {
10    namespace: String,
11    kv: &'a K,
12}
13
14impl<'a, K> Namespaced<'a, K> {
15    pub(crate) const fn new(namespace: String, kv: &'a K) -> Self {
16        Self { namespace, kv }
17    }
18}
19
20#[async_trait]
21impl<'a, K> KeyValue for Namespaced<'a, K>
22where
23    K: KeyValue,
24{
25    fn execute_key_operation(&self, op: KeyOperation) -> Result<Output, Error> {
26        self.kv.execute_key_operation(op)
27    }
28
29    fn key_namespace(&self) -> Option<&'_ str> {
30        Some(&self.namespace)
31    }
32
33    fn with_key_namespace(&'_ self, namespace: &str) -> Namespaced<'_, Self>
34    where
35        Self: Sized,
36    {
37        Namespaced {
38            namespace: format!("{}\u{0}{namespace}", self.namespace),
39            kv: self,
40        }
41    }
42}
43
44#[async_trait]
45impl<'a, K> AsyncKeyValue for Namespaced<'a, K>
46where
47    K: AsyncKeyValue,
48{
49    async fn execute_key_operation(&self, op: KeyOperation) -> Result<Output, Error> {
50        self.kv.execute_key_operation(op).await
51    }
52
53    fn key_namespace(&self) -> Option<&'_ str> {
54        Some(&self.namespace)
55    }
56
57    fn with_key_namespace(&'_ self, namespace: &str) -> Namespaced<'_, Self>
58    where
59        Self: Sized,
60    {
61        Namespaced {
62            namespace: format!("{}\u{0}{namespace}", self.namespace),
63            kv: self,
64        }
65    }
66}