1
use async_trait::async_trait;
2

            
3
use super::{KeyOperation, KeyValue, Output};
4
use crate::keyvalue::AsyncKeyValue;
5
use crate::Error;
6

            
7
/// A namespaced key-value store. All operations performed with this will be
8
/// separate from other namespaces.
9
pub struct Namespaced<'a, K> {
10
    namespace: String,
11
    kv: &'a K,
12
}
13

            
14
impl<'a, K> Namespaced<'a, K> {
15
34
    pub(crate) const fn new(namespace: String, kv: &'a K) -> Self {
16
34
        Self { namespace, kv }
17
34
    }
18
}
19

            
20
#[async_trait]
21
impl<'a, K> KeyValue for Namespaced<'a, K>
22
where
23
    K: KeyValue,
24
{
25
244
    fn execute_key_operation(&self, op: KeyOperation) -> Result<Output, Error> {
26
244
        self.kv.execute_key_operation(op)
27
244
    }
28

            
29
244
    fn key_namespace(&self) -> Option<&'_ str> {
30
244
        Some(&self.namespace)
31
244
    }
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]
45
impl<'a, K> AsyncKeyValue for Namespaced<'a, K>
46
where
47
    K: AsyncKeyValue,
48
{
49
406
    async fn execute_key_operation(&self, op: KeyOperation) -> Result<Output, Error> {
50
413
        self.kv.execute_key_operation(op).await
51
1218
    }
52

            
53
406
    fn key_namespace(&self) -> Option<&'_ str> {
54
406
        Some(&self.namespace)
55
406
    }
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
}