1use std::fmt;
4use std::str;
5
6#[cfg(test)]
7use proptest_derive::Arbitrary;
8
9use super::HexRepr;
10use super::Key;
11use super::Value;
12use crate::proto::kvrpcpb;
13
14#[derive(Default, Clone, Eq, PartialEq, Hash)]
29#[cfg_attr(test, derive(Arbitrary))]
30pub struct KvPair(pub Key, pub Value);
31
32impl KvPair {
33 #[inline]
35 pub fn new(key: impl Into<Key>, value: impl Into<Value>) -> Self {
36 KvPair(key.into(), value.into())
37 }
38
39 #[inline]
41 pub fn key(&self) -> &Key {
42 &self.0
43 }
44
45 #[inline]
47 pub fn value(&self) -> &Value {
48 &self.1
49 }
50
51 #[inline]
53 pub fn into_key(self) -> Key {
54 self.0
55 }
56
57 #[inline]
59 pub fn into_value(self) -> Value {
60 self.1
61 }
62
63 #[inline]
65 pub fn key_mut(&mut self) -> &mut Key {
66 &mut self.0
67 }
68
69 #[inline]
71 pub fn value_mut(&mut self) -> &mut Value {
72 &mut self.1
73 }
74
75 #[inline]
77 pub fn set_key(&mut self, k: impl Into<Key>) {
78 self.0 = k.into();
79 }
80
81 #[inline]
83 pub fn set_value(&mut self, v: impl Into<Value>) {
84 self.1 = v.into();
85 }
86}
87
88impl<K, V> From<(K, V)> for KvPair
89where
90 K: Into<Key>,
91 V: Into<Value>,
92{
93 fn from((k, v): (K, V)) -> Self {
94 KvPair(k.into(), v.into())
95 }
96}
97
98impl From<KvPair> for (Key, Value) {
99 fn from(pair: KvPair) -> Self {
100 (pair.0, pair.1)
101 }
102}
103
104impl From<KvPair> for Key {
105 fn from(pair: KvPair) -> Self {
106 pair.0
107 }
108}
109
110impl From<kvrpcpb::KvPair> for KvPair {
111 fn from(pair: kvrpcpb::KvPair) -> Self {
112 KvPair(Key::from(pair.key), pair.value)
113 }
114}
115
116impl From<KvPair> for kvrpcpb::KvPair {
117 fn from(pair: KvPair) -> Self {
118 let mut result = kvrpcpb::KvPair::default();
119 let (key, value) = pair.into();
120 result.key = key.into();
121 result.value = value;
122 result
123 }
124}
125
126impl AsRef<Key> for KvPair {
127 fn as_ref(&self) -> &Key {
128 &self.0
129 }
130}
131
132impl AsRef<Value> for KvPair {
133 fn as_ref(&self) -> &Value {
134 &self.1
135 }
136}
137
138impl fmt::Debug for KvPair {
139 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
140 let KvPair(key, value) = self;
141 match str::from_utf8(value) {
142 Ok(s) => write!(f, "KvPair({}, {:?})", HexRepr(&key.0), s),
143 Err(_) => write!(f, "KvPair({}, {})", HexRepr(&key.0), HexRepr(value)),
144 }
145 }
146}