cfx_internal_common/
block_data_db_encoding.rs

1// Copyright 2020 Conflux Foundation. All rights reserved.
2// Conflux is free software and distributed under GNU General Public License.
3// See http://www.gnu.org/licenses/
4
5pub trait DatabaseEncodable {
6    fn db_encode(&self) -> Bytes;
7}
8
9pub trait DatabaseDecodable: Sized {
10    fn db_decode(bytes: &[u8]) -> Result<Self, DecoderError>;
11}
12
13#[macro_export]
14macro_rules! impl_db_encoding_as_rlp {
15    ($type:ty) => {
16        impl $crate::DatabaseEncodable for $type {
17            fn db_encode(&self) -> Vec<u8> { rlp::encode(self) }
18        }
19
20        impl $crate::DatabaseDecodable for $type {
21            fn db_decode(bytes: &[u8]) -> Result<$type, DecoderError> {
22                rlp::decode(bytes)
23            }
24        }
25    };
26}
27
28impl_db_encoding_as_rlp!(H256);
29impl_db_encoding_as_rlp!(u64);
30impl_db_encoding_as_rlp!(TransactionIndex);
31
32impl DatabaseDecodable for BlockHeader {
33    fn db_decode(bytes: &[u8]) -> Result<Self, DecoderError> {
34        BlockHeader::decode_with_pow_hash(bytes)
35    }
36}
37
38impl DatabaseEncodable for BlockHeader {
39    fn db_encode(&self) -> Bytes {
40        let mut rlp_stream = RlpStream::new();
41        self.stream_rlp_with_pow_hash(&mut rlp_stream);
42        rlp_stream.drain()
43    }
44}
45
46use cfx_bytes::Bytes;
47use cfx_types::H256;
48use primitives::{BlockHeader, TransactionIndex};
49use rlp::*;