cfxcore/pos/consensus/consensusdb/schema/single_entry/
mod.rs

1// Copyright (c) The Diem Core Contributors
2// SPDX-License-Identifier: Apache-2.0
3
4// Copyright 2021 Conflux Foundation. All rights reserved.
5// Conflux is free software and distributed under GNU General Public License.
6// See http://www.gnu.org/licenses/
7
8//! This module defines physical storage schema for any single-entry data.
9//!
10//! There will be only one row in this column family for each type of data.
11//! The key will be a serialized enum type designating the data type and should
12//! not have any meaning and be used.
13//!
14//! ```text
15//! |<-------key------->|<-----value----->|
16//! | single entry key  | raw value bytes |
17//! ```
18
19use super::{ensure_slice_len_eq, SINGLE_ENTRY_CF_NAME};
20use anyhow::{format_err, Result};
21use byteorder::ReadBytesExt;
22use num_derive::{FromPrimitive, ToPrimitive};
23use num_traits::{FromPrimitive, ToPrimitive};
24use schemadb::{
25    define_schema,
26    schema::{KeyCodec, ValueCodec},
27};
28use std::mem::size_of;
29
30define_schema!(
31    SingleEntrySchema,
32    SingleEntryKey,
33    Vec<u8>,
34    SINGLE_ENTRY_CF_NAME
35);
36
37#[derive(Debug, Eq, PartialEq, FromPrimitive, ToPrimitive)]
38#[repr(u8)]
39pub enum SingleEntryKey {
40    // Used to store the highest timeout certificate
41    HighestTimeoutCertificate = 0,
42    // Used to store the last vote
43    LastVoteMsg = 1,
44}
45
46impl KeyCodec<SingleEntrySchema> for SingleEntryKey {
47    fn encode_key(&self) -> Result<Vec<u8>> {
48        Ok(vec![self
49            .to_u8()
50            .ok_or_else(|| format_err!("ToPrimitive failed."))?])
51    }
52
53    fn decode_key(mut data: &[u8]) -> Result<Self> {
54        ensure_slice_len_eq(data, size_of::<u8>())?;
55        let key = data.read_u8()?;
56        SingleEntryKey::from_u8(key)
57            .ok_or_else(|| format_err!("FromPrimitive failed."))
58    }
59}
60
61impl ValueCodec<SingleEntrySchema> for Vec<u8> {
62    fn encode_value(&self) -> Result<Vec<u8>> { Ok(self.clone()) }
63
64    fn decode_value(data: &[u8]) -> Result<Self> { Ok(data.to_vec()) }
65}
66
67#[cfg(test)]
68mod test;