Skip to content

Commit

Permalink
feat: couple convenience functions for nested cache dbs
Browse files Browse the repository at this point in the history
  • Loading branch information
prestwich committed Nov 13, 2024
1 parent bbc8d81 commit dc9068e
Showing 1 changed file with 36 additions and 0 deletions.
36 changes: 36 additions & 0 deletions crates/database/src/in_memory_db.rs
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,38 @@ impl<ExtDB: Default> Default for CacheDB<ExtDB> {
}
}

impl<ExtDb> CacheDB<CacheDB<ExtDb>> {
/// Flatten a nested cache by applying the outer cache to the inner cache.
///
/// The behavior is as follows:
/// - Accounts are overridden with outer accounts
/// - Contracts are overridden with outer contracts
/// - Logs are appended
/// - Block hashes are overridden with outer block hashes
pub fn flatten(self) -> CacheDB<ExtDb> {
let CacheDB {
accounts,
contracts,
logs,
block_hashes,
db: mut inner,
} = self;

inner.accounts.extend(accounts);
inner.contracts.extend(contracts);
inner.logs.extend(logs);
inner.block_hashes.extend(block_hashes);
inner
}

/// Discard the outer cache and return the inner cache.
pub fn discard_outer(self) -> CacheDB<ExtDb> {
self.db
}
}

impl<ExtDB> CacheDB<ExtDB> {
/// Create a new cache with the given external database.
pub fn new(db: ExtDB) -> Self {
let mut contracts = HashMap::default();
contracts.insert(KECCAK_EMPTY, Bytecode::default());
Expand Down Expand Up @@ -79,6 +110,11 @@ impl<ExtDB> CacheDB<ExtDB> {
self.insert_contract(&mut info);
self.accounts.entry(address).or_default().info = info;
}

/// Wrap the cache in a [CacheDB], creating a nested cache.
pub fn nest(self) -> CacheDB<Self> {
CacheDB::new(self)
}
}

impl<ExtDB: DatabaseRef> CacheDB<ExtDB> {
Expand Down

0 comments on commit dc9068e

Please sign in to comment.