redgold_schema/
proto_serde.rs1use crate::structs::{ErrorCode, Hash, HashType};
2use crate::{ErrorInfoContext, HashClear, RgResult};
3use prost::Message;
4use std::fmt::Display;
5
6pub trait ProtoSerde
7 where Self: Message + Default,
8{
9 fn proto_serialize(&self) -> Vec<u8>;
10 fn vec(&self) -> Vec<u8>;
11
12 fn proto_serialize_hex(&self) -> String;
13 fn hex(&self) -> String;
14 fn proto_deserialize(bytes: Vec<u8>) -> RgResult<Self>;
15 fn from_bytes(bytes: Vec<u8>) -> RgResult<Self>;
16 fn from_bytes_ref(bytes: &Vec<u8>) -> RgResult<Self>;
17
18 fn proto_deserialize_hex(s: impl Into<String>) -> RgResult<Self>;
19 fn from_hex(s: impl Into<String>) -> RgResult<Self>;
20 fn proto_deserialize_ref(bytes: &Vec<u8>) -> RgResult<Self>;
21
22 fn to_hashed(&self) -> Hash {
23 let mut h = Hash::digest(self.vec());
24 h.hash_type = HashType::Proto as i32;
25 h
26 }
27}
28
29impl<T> ProtoSerde for T
30where T: Message + Default {
31 fn proto_serialize(&self) -> Vec<u8> {
32 self.encode_to_vec()
33 }
34
35 fn vec(&self) -> Vec<u8> {
36 self.proto_serialize()
37 }
38
39 fn proto_serialize_hex(&self) -> String {
40 hex::encode(self.proto_serialize())
41 }
42
43 fn hex(&self) -> String {
44 self.proto_serialize_hex()
45 }
46
47 fn proto_deserialize(bytes: Vec<u8>) -> RgResult<Self> {
48 T::decode(&*bytes)
49 .map_err(|e|
50 crate::error_message(ErrorCode::ProtoDecoderFailure, e.to_string()))
51 }
52
53 fn from_bytes(bytes: Vec<u8>) -> RgResult<Self> {
54 Self::proto_deserialize(bytes)
55 }
56
57 fn from_bytes_ref(bytes: &Vec<u8>) -> RgResult<Self> {
58 Self::proto_deserialize_ref(bytes)
59 }
60
61 fn proto_deserialize_hex(s: impl Into<String>) -> RgResult<Self> {
62 hex::decode(s.into())
63 .error_info("hex decode")
64 .and_then(|v| T::proto_deserialize(v))
65 }
66
67 fn from_hex(s: impl Into<String>) -> RgResult<Self> {
68 Self::proto_deserialize_hex(s)
69 }
70
71 fn proto_deserialize_ref(bytes: &Vec<u8>) -> RgResult<Self> {
72 T::decode(&**bytes)
73 .map_err(|e|
74 crate::error_message(ErrorCode::ProtoDecoderFailure, e.to_string()))
75 }
76
77}
78
79
80pub trait ProtoHashable
81where
82 Self: HashClear + Clone + Message + Default,
83{
84 fn calculate_hash(&self) -> Hash;
87 fn div_mod(&self, bucket: usize) -> i64;
88}
89
90impl<T> ProtoHashable for T
91where
92 T: HashClear + Clone + Message + Default,
93{
94 fn calculate_hash(&self) -> Hash {
105 let mut clone = self.clone();
106 clone.hash_clear();
107 let input = clone.proto_serialize();
108 Hash::digest(input)
109 }
110
111 fn div_mod(&self, bucket: usize) -> i64 {
112 self.calculate_hash().div_mod(bucket)
113 }
114}
115