1
use async_trait::async_trait;
2

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

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

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

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

            
28
244
    fn key_namespace(&self) -> Option<&'_ str> {
29
244
        Some(&self.namespace)
30
244
    }
31

            
32
    fn with_key_namespace(&'_ self, namespace: &str) -> Namespaced<'_, Self>
33
    where
34
        Self: Sized,
35
    {
36
        Namespaced {
37
            namespace: format!("{}\u{0}{}", self.namespace, namespace),
38
            kv: self,
39
        }
40
    }
41
}
42

            
43
#[async_trait]
44
impl<'a, K> AsyncKeyValue for Namespaced<'a, K>
45
where
46
    K: AsyncKeyValue,
47
{
48
406
    async fn execute_key_operation(&self, op: KeyOperation) -> Result<Output, Error> {
49
415
        self.kv.execute_key_operation(op).await
50
812
    }
51

            
52
406
    fn key_namespace(&self) -> Option<&'_ str> {
53
406
        Some(&self.namespace)
54
406
    }
55

            
56
    fn with_key_namespace(&'_ self, namespace: &str) -> Namespaced<'_, Self>
57
    where
58
        Self: Sized,
59
    {
60
        Namespaced {
61
            namespace: format!("{}\u{0}{}", self.namespace, namespace),
62
            kv: self,
63
        }
64
    }
65
}