muta_protocol/fixed_codec/
primitive.rs

1use std::mem;
2
3use byteorder::{ByteOrder, LittleEndian};
4use bytes::{Bytes, BytesMut};
5
6use crate::fixed_codec::{FixedCodec, FixedCodecError};
7use crate::types::{Address, Hash, Metadata};
8use crate::{impl_default_fixed_codec_for, ProtocolResult};
9
10// Impl FixedCodec trait for types
11impl_default_fixed_codec_for!(primitive, [Hash, Address, Metadata]);
12
13impl FixedCodec for bool {
14    fn encode_fixed(&self) -> ProtocolResult<Bytes> {
15        let bs = if *self {
16            [1u8; mem::size_of::<u8>()]
17        } else {
18            [0u8; mem::size_of::<u8>()]
19        };
20
21        Ok(BytesMut::from(bs.as_ref()).freeze())
22    }
23
24    fn decode_fixed(bytes: Bytes) -> ProtocolResult<Self> {
25        let u = *bytes.to_vec().get(0).ok_or(FixedCodecError::DecodeBool)?;
26
27        match u {
28            0 => Ok(false),
29            1 => Ok(true),
30            _ => Err(FixedCodecError::DecodeBool.into()),
31        }
32    }
33}
34
35impl FixedCodec for u8 {
36    fn encode_fixed(&self) -> ProtocolResult<Bytes> {
37        Ok(BytesMut::from([*self].as_ref()).freeze())
38    }
39
40    fn decode_fixed(bytes: Bytes) -> ProtocolResult<Self> {
41        let u = *bytes.to_vec().get(0).ok_or(FixedCodecError::DecodeUint8)?;
42
43        Ok(u)
44    }
45}
46
47impl FixedCodec for u32 {
48    fn encode_fixed(&self) -> ProtocolResult<Bytes> {
49        let mut buf = [0u8; mem::size_of::<u32>()];
50        LittleEndian::write_u32(&mut buf, *self);
51
52        Ok(BytesMut::from(buf.as_ref()).freeze())
53    }
54
55    fn decode_fixed(bytes: Bytes) -> ProtocolResult<Self> {
56        Ok(LittleEndian::read_u32(bytes.as_ref()))
57    }
58}
59
60impl FixedCodec for u64 {
61    fn encode_fixed(&self) -> ProtocolResult<Bytes> {
62        let mut buf = [0u8; mem::size_of::<u64>()];
63        LittleEndian::write_u64(&mut buf, *self);
64
65        Ok(BytesMut::from(buf.as_ref()).freeze())
66    }
67
68    fn decode_fixed(bytes: Bytes) -> ProtocolResult<Self> {
69        Ok(LittleEndian::read_u64(bytes.as_ref()))
70    }
71}
72
73impl FixedCodec for String {
74    fn encode_fixed(&self) -> ProtocolResult<Bytes> {
75        Ok(Bytes::from(self.clone()))
76    }
77
78    fn decode_fixed(bytes: Bytes) -> ProtocolResult<Self> {
79        String::from_utf8(bytes.to_vec()).map_err(|e| FixedCodecError::StringUTF8(e).into())
80    }
81}
82
83impl FixedCodec for Bytes {
84    fn encode_fixed(&self) -> ProtocolResult<Bytes> {
85        Ok(self.clone())
86    }
87
88    fn decode_fixed(bytes: Bytes) -> ProtocolResult<Self> {
89        Ok(bytes)
90    }
91}
92
93// AssetID, MerkleRoot are alias of Hash type
94impl rlp::Encodable for Hash {
95    fn rlp_append(&self, s: &mut rlp::RlpStream) {
96        s.begin_list(1).append(&self.as_bytes().to_vec());
97    }
98}
99
100impl rlp::Decodable for Hash {
101    fn decode(r: &rlp::Rlp) -> Result<Self, rlp::DecoderError> {
102        let hash = Hash::from_bytes(BytesMut::from(r.at(0)?.data()?).freeze())
103            .map_err(|_| rlp::DecoderError::RlpInvalidLength)?;
104        Ok(hash)
105    }
106}
107
108impl rlp::Encodable for Address {
109    fn rlp_append(&self, s: &mut rlp::RlpStream) {
110        s.begin_list(1).append(&self.as_bytes().to_vec());
111    }
112}
113
114impl rlp::Decodable for Address {
115    fn decode(r: &rlp::Rlp) -> Result<Self, rlp::DecoderError> {
116        let address = Address::from_bytes(BytesMut::from(r.at(0)?.data()?).freeze())
117            .map_err(|_| rlp::DecoderError::RlpInvalidLength)?;
118
119        Ok(address)
120    }
121}
122
123impl rlp::Encodable for Metadata {
124    fn rlp_append(&self, s: &mut rlp::RlpStream) {
125        s.begin_list(5)
126            .append(&self.chain_id)
127            .append_list(&self.verifier_list)
128            .append(&self.consensus_interval)
129            .append(&self.cycles_limit)
130            .append(&self.cycles_price);
131    }
132}
133
134impl rlp::Decodable for Metadata {
135    fn decode(r: &rlp::Rlp) -> Result<Self, rlp::DecoderError> {
136        let chain_id: Hash = r.at(0)?.as_val()?;
137        let verifier_list: Vec<Address> = r.at(1)?.as_list()?;
138        let consensus_interval = r.at(2)?.as_val()?;
139        let cycles_limit = r.at(3)?.as_val()?;
140        let cycles_price = r.at(4)?.as_val()?;
141
142        Ok(Self {
143            chain_id,
144            verifier_list,
145            consensus_interval,
146            cycles_limit,
147            cycles_price,
148        })
149    }
150}