@@ -138,9 +138,23 @@ impl<T: MarfTrieId> TrieCacheState<T> {
138
138
self . block_hash_cache . get ( & block_id) . cloned ( )
139
139
}
140
140
141
- /// Return the HashMap Entry for a block_id
142
- pub fn entry_block_hash ( & mut self , block_id : u32 ) -> Entry < ' _ , u32 , T > {
143
- self . block_hash_cache . entry ( block_id)
141
+ /// Get cached entry for a block hash, given its ID, or, if not
142
+ /// found, use `lookup` to get the corresponding block hash and
143
+ /// store it in the cache
144
+ pub fn get_block_hash_caching < E , F : FnOnce ( u32 ) -> Result < T , E > > (
145
+ & mut self ,
146
+ id : u32 ,
147
+ lookup : F ,
148
+ ) -> Result < & T , E > {
149
+ match self . block_hash_cache . entry ( id) {
150
+ Entry :: Occupied ( occupied_entry) => Ok ( occupied_entry. into_mut ( ) ) ,
151
+ Entry :: Vacant ( vacant_entry) => {
152
+ let block_hash = lookup ( id) ?;
153
+ let block_hash_ref = vacant_entry. insert ( block_hash. clone ( ) ) ;
154
+ self . block_id_cache . insert ( block_hash, id) ;
155
+ Ok ( block_hash_ref)
156
+ }
157
+ }
144
158
}
145
159
146
160
/// Cache a block hash, given its ID
@@ -315,9 +329,15 @@ impl<T: MarfTrieId> TrieCache<T> {
315
329
self . state_mut ( ) . load_block_hash ( block_id)
316
330
}
317
331
318
- /// Get entry for a block hash, given its ID
319
- pub fn entry_block_hash < ' a > ( & ' a mut self , block_id : u32 ) -> Entry < ' a , u32 , T > {
320
- self . state_mut ( ) . entry_block_hash ( block_id)
332
+ /// Get cached entry for a block hash, given its ID, or, if not
333
+ /// found, use `lookup` to get the corresponding block hash and
334
+ /// store it in the cache
335
+ pub fn get_block_hash_caching < E , F : FnOnce ( u32 ) -> Result < T , E > > (
336
+ & mut self ,
337
+ id : u32 ,
338
+ lookup : F ,
339
+ ) -> Result < & T , E > {
340
+ self . state_mut ( ) . get_block_hash_caching ( id, lookup)
321
341
}
322
342
323
343
/// Store a block's ID and hash to teh cache.
0 commit comments