lsm_tree/
descriptor_table.rs

1// Copyright (c) 2025-present, fjall-rs
2// This source code is licensed under both the Apache 2.0 and MIT License
3// (found in the LICENSE-* files in the repository)
4
5use crate::GlobalTableId;
6use quick_cache::{sync::Cache as QuickCache, UnitWeighter};
7use std::{fs::File, sync::Arc};
8
9const TAG_BLOCK: u8 = 0;
10const TAG_BLOB: u8 = 1;
11
12type Item = Arc<File>;
13
14#[derive(Eq, std::hash::Hash, PartialEq)]
15struct CacheKey(u8, u64, u64);
16
17/// Caches file descriptors to tables and blob files
18pub struct DescriptorTable {
19    inner: QuickCache<CacheKey, Item, UnitWeighter, rustc_hash::FxBuildHasher>,
20}
21
22impl DescriptorTable {
23    #[must_use]
24    pub fn new(capacity: usize) -> Self {
25        use quick_cache::sync::DefaultLifecycle;
26
27        let quick_cache = QuickCache::with(
28            1_000,
29            capacity as u64,
30            UnitWeighter,
31            rustc_hash::FxBuildHasher,
32            DefaultLifecycle::default(),
33        );
34
35        Self { inner: quick_cache }
36    }
37
38    pub(crate) fn len(&self) -> usize {
39        self.inner.len()
40    }
41
42    #[must_use]
43    pub fn access_for_table(&self, id: &GlobalTableId) -> Option<Arc<File>> {
44        let key = CacheKey(TAG_BLOCK, id.tree_id(), id.table_id());
45        self.inner.get(&key)
46    }
47
48    pub fn insert_for_table(&self, id: GlobalTableId, item: Item) {
49        let key = CacheKey(TAG_BLOCK, id.tree_id(), id.table_id());
50        self.inner.insert(key, item);
51    }
52
53    #[must_use]
54    pub fn access_for_blob_file(&self, id: &GlobalTableId) -> Option<Arc<File>> {
55        let key = CacheKey(TAG_BLOB, id.tree_id(), id.table_id());
56        self.inner.get(&key)
57    }
58
59    pub fn insert_for_blob_file(&self, id: GlobalTableId, item: Item) {
60        let key = CacheKey(TAG_BLOB, id.tree_id(), id.table_id());
61        self.inner.insert(key, item);
62    }
63}