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    #[doc(hidden)]
39    pub fn clear(&self) {
40        self.inner.clear();
41    }
42
43    #[must_use]
44    pub fn access_for_table(&self, id: &GlobalTableId) -> Option<Arc<File>> {
45        let key = CacheKey(TAG_BLOCK, id.tree_id(), id.table_id());
46        self.inner.get(&key)
47    }
48
49    pub fn insert_for_table(&self, id: GlobalTableId, item: Item) {
50        let key = CacheKey(TAG_BLOCK, id.tree_id(), id.table_id());
51        self.inner.insert(key, item);
52    }
53
54    #[must_use]
55    pub fn access_for_blob_file(&self, id: &GlobalTableId) -> Option<Arc<File>> {
56        let key = CacheKey(TAG_BLOB, id.tree_id(), id.table_id());
57        self.inner.get(&key)
58    }
59
60    pub fn insert_for_blob_file(&self, id: GlobalTableId, item: Item) {
61        let key = CacheKey(TAG_BLOB, id.tree_id(), id.table_id());
62        self.inner.insert(key, item);
63    }
64}