Skip to main content

miden_node_utils/
lru_cache.rs

1use std::hash::Hash;
2use std::num::NonZeroUsize;
3use std::sync::Arc;
4
5use lru::LruCache as InnerCache;
6use tokio::sync::{Mutex, MutexGuard};
7use tracing::instrument;
8
9/// A newtype wrapper around an LRU cache. Ensures that the cache lock is not held across
10/// await points.
11#[derive(Clone)]
12pub struct LruCache<K, V>(Arc<Mutex<InnerCache<K, V>>>);
13
14impl<K, V> LruCache<K, V>
15where
16    K: Hash + Eq,
17    V: Clone,
18{
19    /// Creates a new cache with the given capacity.
20    pub fn new(capacity: NonZeroUsize) -> Self {
21        Self(Arc::new(Mutex::new(InnerCache::new(capacity))))
22    }
23
24    /// Retrieves a value from the cache.
25    pub async fn get(&self, key: &K) -> Option<V> {
26        self.lock().await.get(key).cloned()
27    }
28
29    /// Puts a value into the cache.
30    pub async fn put(&self, key: K, value: V) {
31        self.lock().await.put(key, value);
32    }
33
34    #[instrument(name = "lru.lock", skip_all)]
35    async fn lock(&self) -> MutexGuard<'_, InnerCache<K, V>> {
36        self.0.lock().await
37    }
38}