pos_ledger_db/schema/block_by_epoch_and_round/
mod.rs1use crate::schema::{ensure_slice_len_eq, BLOCK_BY_EPOCH_AND_ROUND_CF_NAME};
9use anyhow::Result;
10use byteorder::{BigEndian, ReadBytesExt, WriteBytesExt};
11use diem_crypto::HashValue;
12use schemadb::{
13 define_schema,
14 schema::{KeyCodec, ValueCodec},
15};
16use std::mem::size_of;
17
18define_schema!(
19 BlockByEpochAndRoundSchema,
20 Key, HashValue,
22 BLOCK_BY_EPOCH_AND_ROUND_CF_NAME
23);
24
25type Key = (u64, u64);
27
28impl KeyCodec<BlockByEpochAndRoundSchema> for Key {
29 fn encode_key(&self) -> Result<Vec<u8>> {
30 let (epoch, round) = *self;
31
32 let mut encoded_key = Vec::with_capacity(size_of::<u64>() * 2);
33 encoded_key.write_u64::<BigEndian>(epoch)?;
34 encoded_key.write_u64::<BigEndian>(round)?;
35 Ok(encoded_key)
36 }
37
38 fn decode_key(data: &[u8]) -> Result<Self> {
39 ensure_slice_len_eq(data, size_of::<Self>())?;
40
41 let epoch_size = size_of::<u64>();
42
43 let epoch = (&data[..epoch_size]).read_u64::<BigEndian>()?;
44 let round = (&data[epoch_size..]).read_u64::<BigEndian>()?;
45 Ok((epoch, round))
46 }
47}
48
49impl ValueCodec<BlockByEpochAndRoundSchema> for HashValue {
50 fn encode_value(&self) -> Result<Vec<u8>> {
51 bcs::to_bytes(self).map_err(Into::into)
52 }
53
54 fn decode_value(data: &[u8]) -> Result<Self> {
55 bcs::from_bytes(data).map_err(Into::into)
56 }
57}