reth_primitives_traits/
storage.rs

1use alloy_primitives::{B256, U256};
2use revm_primitives::FlaggedStorage;
3
4/// Account storage entry.
5///
6/// `key` is the subkey when used as a value in the `StorageChangeSets` table.
7#[derive(Debug, Default, Copy, Clone, PartialEq, Eq, PartialOrd, Ord)]
8#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
9#[cfg_attr(any(test, feature = "arbitrary"), derive(arbitrary::Arbitrary))]
10#[cfg_attr(any(test, feature = "reth-codec"), reth_codecs::add_arbitrary_tests(compact))]
11pub struct StorageEntry {
12    /// Storage key.
13    pub key: B256,
14    /// Value on storage key.
15    pub value: U256,
16    /// Indicates whether the value is private
17    pub is_private: bool,
18}
19
20impl StorageEntry {
21    /// Create a new `StorageEntry` with given key and value.
22    pub const fn new(key: B256, value: U256, is_private: bool) -> Self {
23        Self { key, value, is_private }
24    }
25
26    /// Convert the storage entry to a flagged storage entry.
27    pub const fn to_flagged_storage(self) -> FlaggedStorage {
28        FlaggedStorage { value: self.value, is_private: self.is_private }
29    }
30}
31
32impl From<(B256, U256, bool)> for StorageEntry {
33    fn from((key, value, is_private): (B256, U256, bool)) -> Self {
34        Self { key, value, is_private }
35    }
36}
37
38impl From<(B256, (U256, bool))> for StorageEntry {
39    fn from((key, (value, is_private)): (B256, (U256, bool))) -> Self {
40        Self { key, value, is_private }
41    }
42}
43
44impl From<StorageEntry> for FlaggedStorage {
45    fn from(entry: StorageEntry) -> Self {
46        Self { value: entry.value, is_private: entry.is_private }
47    }
48}
49
50// NOTE: Removing reth_codec and manually encode subkey
51// and compress second part of the value. If we have compression
52// over whole value (Even SubKey) that would mess up fetching of values with seek_by_key_subkey
53#[cfg(any(test, feature = "reth-codec"))]
54impl reth_codecs::Compact for StorageEntry {
55    fn to_compact<B>(&self, buf: &mut B) -> usize
56    where
57        B: bytes::BufMut + AsMut<[u8]>,
58    {
59        // for now put full bytes and later compress it.
60        buf.put_slice(&self.key[..]);
61        buf.put_u8(self.is_private as u8);
62        self.value.to_compact(buf) + 32 + 1
63    }
64
65    fn from_compact(buf: &[u8], len: usize) -> (Self, &[u8]) {
66        let key = B256::from_slice(&buf[..32]);
67        let is_private = buf[32] != 0;
68        let (value, out) = U256::from_compact(&buf[33..], len - 33);
69        (Self { key, value, is_private }, out)
70    }
71}