1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
// Copyright (c) The Diem Core Contributors
// SPDX-License-Identifier: Apache-2.0

//! This module defines physical storage schema for an index to help us find out which epoch a
//! ledger version is in, by storing a version <-> epoch pair for each version where the epoch
//! number bumps: a pair (`version`, `epoch_num`) indicates that the last version of `epoch_num` is
//! `version`.
//!
//! ```text
//! |<--key-->|<---value-->|
//! | version | epoch_num  |
//! ```
//!
//! `version` is serialized in big endian so that records in RocksDB will be in order of their
//! numeric value.

use crate::schema::{ensure_slice_len_eq, EPOCH_BY_VERSION_CF_NAME};
use anyhow::Result;
use byteorder::{BigEndian, ReadBytesExt};
use diem_types::transaction::Version;
use schemadb::{
    define_schema,
    schema::{KeyCodec, ValueCodec},
};
use std::mem::size_of;

define_schema!(
    EpochByVersionSchema,
    Version,
    u64, // epoch_num
    EPOCH_BY_VERSION_CF_NAME
);

impl KeyCodec<EpochByVersionSchema> for Version {
    fn encode_key(&self) -> Result<Vec<u8>> {
        Ok(self.to_be_bytes().to_vec())
    }

    fn decode_key(mut data: &[u8]) -> Result<Self> {
        ensure_slice_len_eq(data, size_of::<Self>())?;
        Ok(data.read_u64::<BigEndian>()?)
    }
}

impl ValueCodec<EpochByVersionSchema> for u64 {
    fn encode_value(&self) -> Result<Vec<u8>> {
        Ok(self.to_be_bytes().to_vec())
    }

    fn decode_value(mut data: &[u8]) -> Result<Self> {
        ensure_slice_len_eq(data, size_of::<Self>())?;
        Ok(data.read_u64::<BigEndian>()?)
    }
}

#[cfg(test)]
mod test;