Skip to main content

cqlite_core/storage/sstable/reader/
cache.rs

1//! Block caching implementation for SSTable reader
2
3use std::sync::atomic::Ordering;
4
5use super::types::{BlockMeta, CachedBlock, SSTableReader};
6
7impl SSTableReader {
8    /// Calculate current cache hit rate from atomic counters
9    pub(crate) fn calculate_cache_hit_rate(&self) -> f64 {
10        let hits = self.cache_hits.load(Ordering::Relaxed);
11        let misses = self.cache_misses.load(Ordering::Relaxed);
12        let total = hits + misses;
13
14        if total == 0 {
15            0.0
16        } else {
17            hits as f64 / total as f64
18        }
19    }
20
21    /// Increment cache hit counter (thread-safe)
22    /// Currently unused as caching is not yet implemented (always cache miss)
23    #[allow(dead_code)]
24    pub(crate) fn record_cache_hit(&self) {
25        self.cache_hits.fetch_add(1, Ordering::Relaxed);
26    }
27
28    /// Increment cache miss counter (thread-safe)
29    pub(crate) fn record_cache_miss(&self) {
30        self.cache_misses.fetch_add(1, Ordering::Relaxed);
31    }
32
33    /// Get cache statistics for reporting
34    pub fn get_cache_stats(&self) -> (u64, u64, f64) {
35        let hits = self.cache_hits.load(Ordering::Relaxed);
36        let misses = self.cache_misses.load(Ordering::Relaxed);
37        let rate = self.calculate_cache_hit_rate();
38        (hits, misses, rate)
39    }
40
41    /// Estimate current memory usage of the reader
42    pub(crate) fn estimate_memory_usage(&self) -> usize {
43        let base_size = std::mem::size_of::<Self>();
44        let block_cache_size = self
45            .block_cache
46            .values()
47            .map(|block| block.data.len() + std::mem::size_of::<CachedBlock>())
48            .sum::<usize>();
49        let meta_cache_size = self.block_meta_cache.len() * std::mem::size_of::<BlockMeta>();
50
51        base_size + block_cache_size + meta_cache_size
52    }
53
54    /// Clear block caches and log statistics
55    #[allow(dead_code)]
56    pub(crate) fn clear_caches(&mut self) -> (usize, usize) {
57        let cache_entries = self.block_cache.len();
58        let meta_entries = self.block_meta_cache.len();
59
60        self.block_cache.clear();
61        self.block_meta_cache.clear();
62
63        (cache_entries, meta_entries)
64    }
65}