jdb_idx 0.1.1

High-performance SSTable index engine / 高性能 SSTable 索引引擎
Documentation
//! Block cache with LRU eviction / LRU 块缓存

use std::num::NonZeroUsize;

use bytes::Bytes;
use lru::LruCache;
use parking_lot::Mutex;

/// Default cache capacity / 默认缓存容量
const DEFAULT_CAP: NonZeroUsize = NonZeroUsize::new(1024).unwrap();

/// Cache key: (file_id, block_idx)
type CacheKey = (u32, u32);

/// Thread-safe LRU block cache / 线程安全 LRU 块缓存
pub struct BlockCache {
  inner: Mutex<LruCache<CacheKey, Bytes>>,
}

impl BlockCache {
  pub fn new(cap: usize) -> Self {
    // Ensure cap >= 1 / 确保容量至少为 1
    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);
  }

  /// Remove all blocks for a file / 移除文件的所有块
  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")); // Evicts (1, 0)

    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());
  }
}