use std::num::NonZeroUsize;
use std::sync::{Arc, LazyLock, Mutex};
use lru::LruCache;
use crate::Avatar;
pub const CACHE_CAPACITY: usize = 128;
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct CacheKey {
input: String,
sans_env: bool,
part: Option<String>,
theme: Option<String>,
svg_width: i32,
svg_height: i32,
optimize_svg: bool,
}
impl CacheKey {
pub fn new(
input: &str,
sans_env: bool,
part: Option<&str>,
theme: Option<&str>,
svg_width: i32,
svg_height: i32,
optimize_svg: bool,
) -> CacheKey {
CacheKey {
input: input.to_string(),
sans_env,
part: part.map(str::to_string),
theme: theme.map(str::to_string),
svg_width,
svg_height,
optimize_svg,
}
}
}
pub struct AvatarCache;
static CACHE: LazyLock<Mutex<LruCache<CacheKey, Arc<Avatar>>>> = LazyLock::new(|| {
Mutex::new(LruCache::new(
NonZeroUsize::new(CACHE_CAPACITY).expect("cache capacity > 0"),
))
});
impl AvatarCache {
pub fn get(key: &CacheKey) -> Option<Arc<Avatar>> {
CACHE
.lock()
.expect("avatar cache poisoned")
.get(key)
.cloned()
}
pub fn put(key: CacheKey, avatar: Arc<Avatar>) {
CACHE.lock().expect("avatar cache poisoned").put(key, avatar);
}
pub fn size() -> usize {
CACHE.lock().expect("avatar cache poisoned").len()
}
pub fn clear() {
CACHE.lock().expect("avatar cache poisoned").clear();
}
}