use std::collections::HashMap;
#[derive(Debug, Clone, Default)]
pub struct JsonFormatCache {
cache: HashMap<String, String>,
max_entries: usize,
}
impl JsonFormatCache {
pub fn new() -> Self {
Self {
cache: HashMap::new(),
max_entries: 50,
}
}
#[allow(dead_code)]
pub fn with_capacity(max_entries: usize) -> Self {
Self {
cache: HashMap::new(),
max_entries,
}
}
pub fn get_or_format<T: serde::Serialize>(&mut self, key: &str, value: &T) -> &str {
if !self.cache.contains_key(key) {
let formatted = serde_json::to_string_pretty(value).unwrap_or_default();
if self.cache.len() >= self.max_entries {
let to_remove = (self.max_entries / 10).max(1);
let keys: Vec<String> = self.cache.keys().take(to_remove).cloned().collect();
for k in keys {
self.cache.remove(&k);
}
}
self.cache.insert(key.to_string(), formatted);
}
self.cache.get(key).map(|s| s.as_str()).unwrap_or("")
}
pub fn invalidate(&mut self, key: &str) {
self.cache.remove(key);
}
pub fn invalidate_prefix(&mut self, prefix: &str) {
self.cache.retain(|k, _| !k.starts_with(prefix));
}
pub fn clear(&mut self) {
self.cache.clear();
}
#[allow(dead_code)]
pub fn stats(&self) -> (usize, usize) {
(self.cache.len(), self.max_entries)
}
}