forked from nervosnetwork/ckb
/
cachedb.rs
63 lines (56 loc) · 1.56 KB
/
cachedb.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
use ckb_db::{Col, KeyValueDB, Result};
use ckb_util::RwLock;
use fnv::FnvHashMap;
use lru_cache::LruCache;
use std::ops::Range;
type CacheTable = FnvHashMap<Col, LruCache<Vec<u8>, Vec<u8>>>;
pub type CacheCols = (u32, usize);
pub struct CacheDB<T>
where
T: KeyValueDB,
{
db: T,
cache: RwLock<CacheTable>,
}
impl<T> CacheDB<T>
where
T: KeyValueDB,
{
pub fn new(db: T, cols: &[CacheCols]) -> Self {
let mut table = FnvHashMap::with_capacity_and_hasher(cols.len(), Default::default());
for (idx, capacity) in cols {
table.insert(*idx, LruCache::new(*capacity));
}
CacheDB {
db,
cache: RwLock::new(table),
}
}
}
impl<T> KeyValueDB for CacheDB<T>
where
T: KeyValueDB,
{
type Batch = T::Batch;
fn read(&self, col: Col, key: &[u8]) -> Result<Option<Vec<u8>>> {
let cache_guard = self.cache.read();
if let Some(value) = cache_guard
.get(&col)
.and_then(|cache| cache.get(key))
.cloned()
{
return Ok(Some(value));
}
self.db.read(col, key)
}
fn partial_read(&self, col: Col, key: &[u8], range: &Range<usize>) -> Result<Option<Vec<u8>>> {
let cache_guard = self.cache.read();
if let Some(data) = cache_guard.get(&col).and_then(|cache| cache.get(key)) {
return Ok(data.get(range.start..range.end).map(|slice| slice.to_vec()));
}
self.db.partial_read(col, key, range)
}
fn batch(&self) -> Result<Self::Batch> {
self.db.batch()
}
}