etcd_client/namespace/
kv.rs1use crate::error::Result;
2use crate::vec::VecExt;
3use crate::{
4 DeleteOptions, DeleteResponse, GetOptions, GetResponse, KvClient, PutOptions, PutResponse, Txn,
5 TxnResponse,
6};
7
8pub struct KvClientPrefix {
9 pfx: Vec<u8>,
10 kv: KvClient,
11}
12
13impl KvClientPrefix {
14 pub fn new(kv: KvClient, pfx: Vec<u8>) -> Self {
15 Self { pfx, kv }
16 }
17
18 #[inline]
19 fn prefixed_key(&self, key: impl Into<Vec<u8>>) -> Vec<u8> {
20 let mut key = key.into();
21 key.prefix_with(&self.pfx);
22 key
23 }
24
25 pub async fn put(
26 &mut self,
27 key: impl Into<Vec<u8>>,
28 value: impl Into<Vec<u8>>,
29 options: Option<PutOptions>,
30 ) -> Result<PutResponse> {
31 let key = self.prefixed_key(key);
32 let mut resp = self.kv.put(key, value, options).await?;
33 resp.strip_prev_key_prefix(&self.pfx);
34 Ok(resp)
35 }
36
37 pub async fn get(
38 &mut self,
39 key: impl Into<Vec<u8>>,
40 mut options: Option<GetOptions>,
41 ) -> Result<GetResponse> {
42 let key = self.prefixed_key(key);
43 options = options.map(|mut opts| {
44 opts.key_range_end_mut().prefix_range_end_with(&self.pfx);
45 opts
46 });
47 let mut resp = self.kv.get(key, options).await?;
48 resp.strip_kvs_prefix(&self.pfx);
49 Ok(resp)
50 }
51
52 pub async fn delete(
53 &mut self,
54 key: impl Into<Vec<u8>>,
55 mut options: Option<DeleteOptions>,
56 ) -> Result<DeleteResponse> {
57 let key = self.prefixed_key(key);
58 options = options.map(|mut opts| {
59 opts.key_range_end_mut().prefix_range_end_with(&self.pfx);
60 opts
61 });
62 let mut resp = self.kv.delete(key, options).await?;
63 resp.strip_prev_kvs_prefix(&self.pfx);
64 Ok(resp)
65 }
66
67 pub async fn txn(&mut self, mut txn: Txn) -> Result<TxnResponse> {
68 txn.prefix_with(&self.pfx);
69 let mut resp = self.kv.txn(txn).await?;
70 resp.strip_key_prefix(&self.pfx);
71 Ok(resp)
72 }
73}