replace lru with schnellru (#14539)

This commit is contained in:
Qinxuan Chen
2023-07-10 05:24:23 +08:00
committed by GitHub
parent 6dd625d568
commit 6d2c1ed719
11 changed files with 58 additions and 71 deletions
@@ -18,13 +18,12 @@
//! Implements tree backend, cached header metadata and algorithms
//! to compute routes efficiently over the tree of headers.
use lru::LruCache;
use parking_lot::RwLock;
use schnellru::{ByLength, LruMap};
use sp_runtime::traits::{Block as BlockT, Header, NumberFor, One};
use std::num::NonZeroUsize;
/// Set to the expected max difference between `best` and `finalized` blocks at sync.
const LRU_CACHE_SIZE: usize = 5_000;
const LRU_CACHE_SIZE: u32 = 5_000;
/// Get lowest common ancestor between two blocks in the tree.
///
@@ -243,20 +242,19 @@ pub trait HeaderMetadata<Block: BlockT> {
/// Caches header metadata in an in-memory LRU cache.
pub struct HeaderMetadataCache<Block: BlockT> {
cache: RwLock<LruCache<Block::Hash, CachedHeaderMetadata<Block>>>,
cache: RwLock<LruMap<Block::Hash, CachedHeaderMetadata<Block>>>,
}
impl<Block: BlockT> HeaderMetadataCache<Block> {
/// Creates a new LRU header metadata cache with `capacity`.
pub fn new(capacity: NonZeroUsize) -> Self {
HeaderMetadataCache { cache: RwLock::new(LruCache::new(capacity)) }
pub fn new(capacity: u32) -> Self {
HeaderMetadataCache { cache: RwLock::new(LruMap::new(ByLength::new(capacity))) }
}
}
impl<Block: BlockT> Default for HeaderMetadataCache<Block> {
fn default() -> Self {
let cap = NonZeroUsize::new(LRU_CACHE_SIZE).expect("cache capacity is not zero");
HeaderMetadataCache { cache: RwLock::new(LruCache::new(cap)) }
HeaderMetadataCache { cache: RwLock::new(LruMap::new(ByLength::new(LRU_CACHE_SIZE))) }
}
}
@@ -266,11 +264,11 @@ impl<Block: BlockT> HeaderMetadataCache<Block> {
}
pub fn insert_header_metadata(&self, hash: Block::Hash, metadata: CachedHeaderMetadata<Block>) {
self.cache.write().put(hash, metadata);
self.cache.write().insert(hash, metadata);
}
pub fn remove_header_metadata(&self, hash: Block::Hash) {
self.cache.write().pop(&hash);
self.cache.write().remove(&hash);
}
}