commonware_storage/qmdb/any/operation/update/
ordered.rs1use crate::qmdb::any::{
2 operation::{update::sealed::Sealed, Update as UpdateTrait},
3 value::{FixedEncoding, ValueEncoding, VariableEncoding},
4 FixedValue, VariableValue,
5};
6use bytes::{Buf, BufMut};
7use commonware_codec::{
8 Encode as _, EncodeSize, Error as CodecError, FixedSize, Read, ReadExt as _, Write,
9};
10use commonware_utils::{hex, Array};
11use std::fmt;
12
13#[derive(Clone, PartialEq, Debug, Eq)]
14pub struct Update<K: Array + Ord, V: ValueEncoding> {
15 pub key: K,
16 pub value: V::Value,
17 pub next_key: K,
18}
19
20#[cfg(feature = "arbitrary")]
21impl<K: Array + Ord, V: ValueEncoding> arbitrary::Arbitrary<'_> for Update<K, V>
22where
23 K: for<'a> arbitrary::Arbitrary<'a>,
24 V::Value: for<'a> arbitrary::Arbitrary<'a>,
25{
26 fn arbitrary(u: &mut arbitrary::Unstructured<'_>) -> arbitrary::Result<Self> {
27 Ok(Self {
28 key: u.arbitrary()?,
29 value: u.arbitrary()?,
30 next_key: u.arbitrary()?,
31 })
32 }
33}
34
35impl<K: Array, V: ValueEncoding> Sealed for Update<K, V> {}
36
37impl<K: Array, V: ValueEncoding> UpdateTrait<K, V> for Update<K, V> {
38 fn key(&self) -> &K {
39 &self.key
40 }
41
42 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
43 write!(
44 f,
45 "[key:{} next_key:{} value:{}]",
46 self.key,
47 self.next_key,
48 hex(&self.value.encode())
49 )
50 }
51}
52
53impl<K: Array, V: FixedValue> FixedSize for Update<K, FixedEncoding<V>> {
54 const SIZE: usize = K::SIZE + V::SIZE + K::SIZE;
55}
56
57impl<K: Array, V: FixedValue> Write for Update<K, FixedEncoding<V>> {
58 fn write(&self, buf: &mut impl BufMut) {
59 self.key.write(buf);
60 self.value.write(buf);
61 self.next_key.write(buf);
62 }
63}
64
65impl<K: Array, V: FixedValue> Read for Update<K, FixedEncoding<V>> {
66 type Cfg = ();
67
68 fn read_cfg(buf: &mut impl Buf, cfg: &Self::Cfg) -> Result<Self, CodecError> {
69 let key = K::read(buf)?;
70 let value = V::read_cfg(buf, cfg)?;
71 let next_key = K::read(buf)?;
72 Ok(Self {
73 key,
74 value,
75 next_key,
76 })
77 }
78}
79
80impl<K: Array, V: VariableValue> EncodeSize for Update<K, VariableEncoding<V>> {
81 fn encode_size(&self) -> usize {
82 K::SIZE + self.value.encode_size() + K::SIZE
83 }
84}
85
86impl<K: Array, V: VariableValue> Write for Update<K, VariableEncoding<V>> {
87 fn write(&self, buf: &mut impl BufMut) {
88 self.key.write(buf);
89 self.value.write(buf);
90 self.next_key.write(buf);
91 }
92}
93
94impl<K: Array, V: VariableValue> Read for Update<K, VariableEncoding<V>> {
95 type Cfg = <V as Read>::Cfg;
96
97 fn read_cfg(buf: &mut impl Buf, cfg: &Self::Cfg) -> Result<Self, CodecError> {
98 let key = K::read(buf)?;
99 let value = V::read_cfg(buf, cfg)?;
100 let next_key = K::read(buf)?;
101 Ok(Self {
102 key,
103 value,
104 next_key,
105 })
106 }
107}