sqlx_build_trust_core/common/
statement_cache.rs

1use hashlink::lru_cache::LruCache;
2
3/// A cache for prepared statements. When full, the least recently used
4/// statement gets removed.
5#[derive(Debug)]
6pub struct StatementCache<T> {
7    inner: LruCache<String, T>,
8}
9
10impl<T> StatementCache<T> {
11    /// Create a new cache with the given capacity.
12    pub fn new(capacity: usize) -> Self {
13        Self {
14            inner: LruCache::new(capacity),
15        }
16    }
17
18    /// Returns a mutable reference to the value corresponding to the given key
19    /// in the cache, if any.
20    pub fn get_mut(&mut self, k: &str) -> Option<&mut T> {
21        self.inner.get_mut(k)
22    }
23
24    /// Inserts a new statement to the cache, returning the least recently used
25    /// statement id if the cache is full, or if inserting with an existing key,
26    /// the replaced existing statement.
27    pub fn insert(&mut self, k: &str, v: T) -> Option<T> {
28        let mut lru_item = None;
29
30        if self.capacity() == self.len() && !self.contains_key(k) {
31            lru_item = self.remove_lru();
32        } else if self.contains_key(k) {
33            lru_item = self.inner.remove(k);
34        }
35
36        self.inner.insert(k.into(), v);
37
38        lru_item
39    }
40
41    /// The number of statements in the cache.
42    pub fn len(&self) -> usize {
43        self.inner.len()
44    }
45
46    /// Removes the least recently used item from the cache.
47    pub fn remove_lru(&mut self) -> Option<T> {
48        self.inner.remove_lru().map(|(_, v)| v)
49    }
50
51    /// Clear all cached statements from the cache.
52    pub fn clear(&mut self) {
53        self.inner.clear();
54    }
55
56    /// True if cache has a value for the given key.
57    pub fn contains_key(&mut self, k: &str) -> bool {
58        self.inner.contains_key(k)
59    }
60
61    /// Returns the maximum number of statements the cache can hold.
62    pub fn capacity(&self) -> usize {
63        self.inner.capacity()
64    }
65
66    /// Returns true if the cache capacity is more than 0.
67    #[allow(dead_code)] // Only used for some `cfg`s
68    pub fn is_enabled(&self) -> bool {
69        self.capacity() > 0
70    }
71}