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
use async_trait::async_trait;

use super::{KeyOperation, Kv, Output};
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> Kv for Namespaced<'a, K>
where
    K: Kv,
{
    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}{}", self.namespace, namespace),
            kv: self,
        }
    }
}