commonware_storage/qmdb/any/operation/update/
unordered.rs

1use 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, V: ValueEncoding>(pub K, pub V::Value);
15
16#[cfg(feature = "arbitrary")]
17impl<K: Array, V: ValueEncoding> arbitrary::Arbitrary<'_> for Update<K, V>
18where
19    K: for<'a> arbitrary::Arbitrary<'a>,
20    V::Value: for<'a> arbitrary::Arbitrary<'a>,
21{
22    fn arbitrary(u: &mut arbitrary::Unstructured<'_>) -> arbitrary::Result<Self> {
23        Ok(Self(u.arbitrary()?, u.arbitrary()?))
24    }
25}
26
27impl<K: Array, V: ValueEncoding> Sealed for Update<K, V> {}
28
29impl<K: Array, V: ValueEncoding> UpdateTrait<K, V> for Update<K, V> {
30    fn key(&self) -> &K {
31        &self.0
32    }
33
34    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
35        write!(f, "[key:{} value:{}]", self.0, hex(&self.1.encode()))
36    }
37}
38
39impl<K: Array, V: FixedValue> FixedSize for Update<K, FixedEncoding<V>> {
40    const SIZE: usize = K::SIZE + V::SIZE;
41}
42
43impl<K: Array, V: FixedValue> Write for Update<K, FixedEncoding<V>> {
44    fn write(&self, buf: &mut impl BufMut) {
45        self.0.write(buf);
46        self.1.write(buf);
47    }
48}
49
50impl<K: Array, V: FixedValue> Read for Update<K, FixedEncoding<V>> {
51    type Cfg = ();
52
53    fn read_cfg(buf: &mut impl Buf, cfg: &Self::Cfg) -> Result<Self, CodecError> {
54        let key = K::read(buf)?;
55        let value = V::read_cfg(buf, cfg)?;
56        Ok(Self(key, value))
57    }
58}
59
60impl<K: Array, V: VariableValue> EncodeSize for Update<K, VariableEncoding<V>> {
61    fn encode_size(&self) -> usize {
62        K::SIZE + self.1.encode_size()
63    }
64}
65
66impl<K: Array, V: VariableValue> Write for Update<K, VariableEncoding<V>> {
67    fn write(&self, buf: &mut impl BufMut) {
68        self.0.write(buf);
69        self.1.write(buf);
70    }
71}
72
73impl<K: Array, V: VariableValue> Read for Update<K, VariableEncoding<V>> {
74    type Cfg = <V as Read>::Cfg;
75
76    fn read_cfg(buf: &mut impl Buf, cfg: &Self::Cfg) -> Result<Self, CodecError> {
77        let key = K::read(buf)?;
78        let value = V::read_cfg(buf, cfg)?;
79        Ok(Self(key, value))
80    }
81}