use std::num::NonZeroUsize;
use bytes::Bytes;
use lru::LruCache;
use parking_lot::Mutex;
const DEFAULT_CAP: NonZeroUsize = NonZeroUsize::new(1024).unwrap();
type CacheKey = (u32, u32);
pub struct BlockCache {
inner: Mutex<LruCache<CacheKey, Bytes>>,
}
impl BlockCache {
pub fn new(cap: usize) -> Self {
let cap = NonZeroUsize::new(cap.max(1)).unwrap();
Self {
inner: Mutex::new(LruCache::new(cap)),
}
}
#[inline]
pub fn get(&self, file_id: u32, block_idx: u32) -> Option<Bytes> {
self.inner.lock().get(&(file_id, block_idx)).cloned()
}
#[inline]
pub fn put(&self, file_id: u32, block_idx: u32, data: Bytes) {
self.inner.lock().put((file_id, block_idx), data);
}
pub fn evict_file(&self, file_id: u32) {
let mut cache = self.inner.lock();
let keys: Vec<_> = cache
.iter()
.filter(|((fid, _), _)| *fid == file_id)
.map(|(k, _)| *k)
.collect();
for k in keys {
cache.pop(&k);
}
}
#[inline]
pub fn len(&self) -> usize {
self.inner.lock().len()
}
#[inline]
pub fn is_empty(&self) -> bool {
self.inner.lock().is_empty()
}
#[inline]
pub fn clear(&self) {
self.inner.lock().clear();
}
}
impl Default for BlockCache {
fn default() -> Self {
Self::new(DEFAULT_CAP.get())
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn cache_basic() {
let cache = BlockCache::new(2);
cache.put(1, 0, Bytes::from_static(b"block0"));
cache.put(1, 1, Bytes::from_static(b"block1"));
assert_eq!(cache.len(), 2);
assert_eq!(cache.get(1, 0).unwrap().as_ref(), &b"block0"[..]);
assert_eq!(cache.get(1, 1).unwrap().as_ref(), &b"block1"[..]);
assert!(cache.get(1, 2).is_none());
}
#[test]
fn cache_eviction() {
let cache = BlockCache::new(2);
cache.put(1, 0, Bytes::from_static(b"a"));
cache.put(1, 1, Bytes::from_static(b"b"));
cache.put(1, 2, Bytes::from_static(b"c"));
assert!(cache.get(1, 0).is_none());
assert!(cache.get(1, 1).is_some());
assert!(cache.get(1, 2).is_some());
}
#[test]
fn cache_evict_file() {
let cache = BlockCache::new(10);
cache.put(1, 0, Bytes::from_static(b"a"));
cache.put(1, 1, Bytes::from_static(b"b"));
cache.put(2, 0, Bytes::from_static(b"c"));
cache.evict_file(1);
assert!(cache.get(1, 0).is_none());
assert!(cache.get(1, 1).is_none());
assert!(cache.get(2, 0).is_some());
}
}