vtcode_core/prompts/
system_prompt_cache.rs1use lru::LruCache;
2use parking_lot::RwLock;
3use std::collections::hash_map::DefaultHasher;
4use std::hash::{Hash, Hasher};
5use std::num::NonZeroUsize;
6use std::sync::LazyLock;
7
8use crate::prompts::system::SystemPromptReport;
9
10const MAX_SHARD_SIZE: usize = 32;
14const NUM_SHARDS: usize = 16;
15const SHARD_MASK: usize = NUM_SHARDS - 1;
16
17pub struct SystemPromptCache<V: Clone> {
27 shards: [RwLock<LruCache<String, V>>; NUM_SHARDS],
28}
29
30impl<V: Clone> Default for SystemPromptCache<V> {
31 fn default() -> Self {
32 Self::new()
33 }
34}
35
36impl<V: Clone> SystemPromptCache<V> {
37 pub fn new() -> Self {
38 let shard_size = NonZeroUsize::new(MAX_SHARD_SIZE).unwrap_or(NonZeroUsize::MIN);
39 let shard = || RwLock::new(LruCache::new(shard_size));
40 Self { shards: [(); NUM_SHARDS].map(|_| shard()) }
41 }
42
43 #[inline]
44 fn shard_index(key: &str) -> usize {
45 let mut hasher = DefaultHasher::new();
46 key.hash(&mut hasher);
47 (hasher.finish() as usize) & SHARD_MASK
48 }
49
50 pub fn get(&self, key: &str) -> Option<V> {
52 let shard = self.shards[Self::shard_index(key)].read();
53 shard.peek(key).cloned()
54 }
55
56 pub fn insert(&self, key: String, value: V) {
58 let idx = Self::shard_index(&key);
59 let mut shard = self.shards[idx].write();
60 shard.put(key, value);
61 }
62}
63
64pub static PROMPT_CACHE: LazyLock<SystemPromptCache<(String, SystemPromptReport)>> =
71 LazyLock::new(SystemPromptCache::new);