1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
use async_trait::async_trait;

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

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

impl<'a, K> Namespaced<'a, K> {
    pub(crate) const fn new(namespace: String, kv: &'a K) -> Self {
        Self { namespace, kv }
    }
}

#[async_trait]
impl<'a, K> KeyValue for Namespaced<'a, K>
where
    K: KeyValue,
{
    fn execute_key_operation(&self, op: KeyOperation) -> Result<Output, Error> {
        self.kv.execute_key_operation(op)
    }

    fn key_namespace(&self) -> Option<&'_ str> {
        Some(&self.namespace)
    }

    fn with_key_namespace(&'_ self, namespace: &str) -> Namespaced<'_, Self>
    where
        Self: Sized,
    {
        Namespaced {
            namespace: format!("{}\u{0}{namespace}", self.namespace),
            kv: self,
        }
    }
}

#[async_trait]
impl<'a, K> AsyncKeyValue for Namespaced<'a, K>
where
    K: AsyncKeyValue,
{
    async fn execute_key_operation(&self, op: KeyOperation) -> Result<Output, Error> {
        self.kv.execute_key_operation(op).await
    }

    fn key_namespace(&self) -> Option<&'_ str> {
        Some(&self.namespace)
    }

    fn with_key_namespace(&'_ self, namespace: &str) -> Namespaced<'_, Self>
    where
        Self: Sized,
    {
        Namespaced {
            namespace: format!("{}\u{0}{namespace}", self.namespace),
            kv: self,
        }
    }
}