commonware_storage/qmdb/any/operation/
variable.rs1use crate::{
2 merkle::Family,
3 qmdb::{
4 any::{
5 VariableValue,
6 operation::{
7 COMMIT_CONTEXT, DELETE_CONTEXT, Operation, OperationCodec, UPDATE_CONTEXT, Update,
8 update,
9 },
10 value::VariableEncoding,
11 },
12 operation::{
13 Key, commit_variable_payload_size, read_commit_variable, write_commit_variable,
14 },
15 },
16};
17use commonware_codec::{EncodeSize, Error as CodecError, Read, ReadExt as _, Write};
18use commonware_runtime::{Buf, BufMut};
19
20impl<F, V, S> OperationCodec<F, S> for VariableEncoding<V>
21where
22 F: Family,
23 S::Key: Write + Read,
24 V: VariableValue,
25 S: Update<Value = V, ValueEncoding = Self>
26 + Write
27 + Read<Cfg = (<S::Key as Read>::Cfg, <V as Read>::Cfg)>,
28{
29 type ReadCfg = (<S::Key as Read>::Cfg, <V as Read>::Cfg);
30
31 fn write_operation(op: &Operation<F, S>, buf: &mut impl BufMut) {
32 match op {
33 Operation::Delete(k) => {
34 DELETE_CONTEXT.write(buf);
35 k.write(buf);
36 }
37 Operation::Update(p) => {
38 UPDATE_CONTEXT.write(buf);
39 p.write(buf);
40 }
41 Operation::CommitFloor(metadata, floor_loc) => {
42 COMMIT_CONTEXT.write(buf);
43 write_commit_variable(metadata, *floor_loc, buf);
44 }
45 }
46 }
47
48 fn read_operation(
49 buf: &mut impl Buf,
50 cfg: &Self::ReadCfg,
51 ) -> Result<Operation<F, S>, CodecError> {
52 match u8::read(buf)? {
53 DELETE_CONTEXT => {
54 let key = S::Key::read_cfg(buf, &cfg.0)?;
55 Ok(Operation::Delete(key))
56 }
57 UPDATE_CONTEXT => {
58 let payload = S::read_cfg(buf, cfg)?;
59 Ok(Operation::Update(payload))
60 }
61 COMMIT_CONTEXT => {
62 let (metadata, floor_loc) = read_commit_variable(buf, &cfg.1)?;
63 Ok(Operation::CommitFloor(metadata, floor_loc))
64 }
65 e => Err(CodecError::InvalidEnum(e)),
66 }
67 }
68}
69
70impl<F, K, V> EncodeSize for Operation<F, update::Ordered<K, VariableEncoding<V>>>
72where
73 F: Family,
74 K: Key + EncodeSize,
75 V: VariableValue,
76 update::Ordered<K, VariableEncoding<V>>: EncodeSize,
77{
78 fn encode_size(&self) -> usize {
79 1 + match self {
80 Self::Delete(k) => k.encode_size(),
81 Self::Update(p) => p.encode_size(),
82 Self::CommitFloor(v, floor) => commit_variable_payload_size(v, *floor),
83 }
84 }
85}
86
87impl<F, K, V> EncodeSize for Operation<F, update::Unordered<K, VariableEncoding<V>>>
89where
90 F: Family,
91 K: Key + EncodeSize,
92 V: VariableValue,
93 update::Unordered<K, VariableEncoding<V>>: EncodeSize,
94{
95 fn encode_size(&self) -> usize {
96 1 + match self {
97 Self::Delete(k) => k.encode_size(),
98 Self::Update(p) => p.encode_size(),
99 Self::CommitFloor(v, floor) => commit_variable_payload_size(v, *floor),
100 }
101 }
102}