reth_db_api/models/
sharded_key.rs

1//! Sharded key
2use crate::{
3    table::{Decode, Encode},
4    DatabaseError,
5};
6use alloy_primitives::BlockNumber;
7use serde::{Deserialize, Serialize};
8use std::hash::Hash;
9
10/// Number of indices in one shard.
11pub const NUM_OF_INDICES_IN_SHARD: usize = 2_000;
12
13/// Sometimes data can be too big to be saved for a single key. This helps out by dividing the data
14/// into different shards. Example:
15///
16/// `Address | 200` -> data is from block 0 to 200.
17///
18/// `Address | 300` -> data is from block 201 to 300.
19#[derive(Debug, Default, Clone, Eq, PartialEq, Ord, PartialOrd, Serialize, Deserialize, Hash)]
20pub struct ShardedKey<T> {
21    /// The key for this type.
22    pub key: T,
23    /// Highest block number to which `value` is related to.
24    pub highest_block_number: BlockNumber,
25}
26
27impl<T> AsRef<Self> for ShardedKey<T> {
28    fn as_ref(&self) -> &Self {
29        self
30    }
31}
32
33impl<T> ShardedKey<T> {
34    /// Creates a new `ShardedKey<T>`.
35    pub const fn new(key: T, highest_block_number: BlockNumber) -> Self {
36        Self { key, highest_block_number }
37    }
38
39    /// Creates a new key with the highest block number set to maximum.
40    /// This is useful when we want to search the last value for a given key.
41    pub const fn last(key: T) -> Self {
42        Self { key, highest_block_number: u64::MAX }
43    }
44}
45
46impl<T: Encode> Encode for ShardedKey<T> {
47    type Encoded = Vec<u8>;
48
49    fn encode(self) -> Self::Encoded {
50        let mut buf: Vec<u8> = Encode::encode(self.key).into();
51        buf.extend_from_slice(&self.highest_block_number.to_be_bytes());
52        buf
53    }
54}
55
56impl<T: Decode> Decode for ShardedKey<T> {
57    fn decode(value: &[u8]) -> Result<Self, DatabaseError> {
58        let (key, highest_tx_number) = value.split_last_chunk().unwrap();
59        let key = T::decode(key)?;
60        let highest_tx_number = u64::from_be_bytes(*highest_tx_number);
61        Ok(Self::new(key, highest_tx_number))
62    }
63}