pos_ledger_db/schema/event_accumulator/
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 the event accumulator.
9//!
10//! Each version has its own event accumulator and a hash value is stored on
11//! each position within an accumulator. See `storage/accumulator/lib.rs` for
12//! details.
13//!
14//! ```text
15//! |<--------key------->|<-value->|
16//! | version | position |  hash   |
17//! ```
18
19use crate::schema::{ensure_slice_len_eq, EVENT_ACCUMULATOR_CF_NAME};
20use anyhow::Result;
21use byteorder::{BigEndian, ReadBytesExt, WriteBytesExt};
22use diem_crypto::hash::HashValue;
23use diem_types::{proof::position::Position, transaction::Version};
24use schemadb::{
25    define_schema,
26    schema::{KeyCodec, ValueCodec},
27};
28use std::mem::size_of;
29
30define_schema!(
31    EventAccumulatorSchema,
32    Key,
33    HashValue,
34    EVENT_ACCUMULATOR_CF_NAME
35);
36
37type Key = (Version, Position);
38
39impl KeyCodec<EventAccumulatorSchema> for Key {
40    fn encode_key(&self) -> Result<Vec<u8>> {
41        let (version, position) = self;
42
43        let mut encoded_key =
44            Vec::with_capacity(size_of::<Version>() + size_of::<u64>());
45        encoded_key.write_u64::<BigEndian>(*version)?;
46        encoded_key.write_u64::<BigEndian>(position.to_inorder_index())?;
47        Ok(encoded_key)
48    }
49
50    fn decode_key(data: &[u8]) -> Result<Self> {
51        ensure_slice_len_eq(data, size_of::<Self>())?;
52
53        let version_size = size_of::<Version>();
54
55        let version = (&data[..version_size]).read_u64::<BigEndian>()?;
56        let position = (&data[version_size..]).read_u64::<BigEndian>()?;
57        Ok((version, Position::from_inorder_index(position)))
58    }
59}
60
61impl ValueCodec<EventAccumulatorSchema> for HashValue {
62    fn encode_value(&self) -> Result<Vec<u8>> { Ok(self.to_vec()) }
63
64    fn decode_value(data: &[u8]) -> Result<Self> {
65        Self::from_slice(data).map_err(Into::into)
66    }
67}
68
69#[cfg(test)]
70mod test;