use std::sync::Mutex;
use renderer_cache::{Cache, Policy};
use ui_core::{AssetCache, AssetKey};
pub const DEFAULT_BUDGET_BYTES: usize = 8 * 1024 * 1024;
pub struct MemoryCache {
entries: Mutex<Cache<AssetKey, Vec<u8>>>,
}
impl MemoryCache {
pub fn new(capacity_bytes: usize) -> Self {
Self::with_policy(Policy::new(capacity_bytes))
}
pub fn with_policy(policy: Policy) -> Self {
Self {
entries: Mutex::new(Cache::new(policy, Vec::len)),
}
}
pub fn stat(&self) -> renderer_cache::CacheStat {
self.locked().stat("assets")
}
pub fn clear(&self) {
self.locked().clear();
}
fn locked(&self) -> std::sync::MutexGuard<'_, Cache<AssetKey, Vec<u8>>> {
self.entries.lock().unwrap_or_else(|e| e.into_inner())
}
}
impl Default for MemoryCache {
fn default() -> Self {
Self::new(DEFAULT_BUDGET_BYTES)
}
}
impl AssetCache for MemoryCache {
fn get(&self, key: &AssetKey) -> Option<Vec<u8>> {
self.locked().get(key).cloned()
}
fn put(&self, key: &AssetKey, bytes: &[u8]) {
self.locked().insert(key.clone(), bytes.to_vec());
}
}
#[cfg(test)]
#[path = "memory_cache_test.rs"]
mod tests;