use crate::cache::cache_storage_with_get_size::CacheStorageWithGetSize;
use crate::cache::CacheStorage;
use crate::template::Template;
use std::collections::HashMap;
use std::rc::Rc;
#[derive(Default)]
pub struct SoftCacheStorage {
map: HashMap<String, std::rc::Weak<Template>>,
}
impl CacheStorage for SoftCacheStorage {
fn get(&mut self, key: &str) -> Option<Rc<Template>> {
self.map.get(key)?.upgrade()
}
fn put(&mut self, key: &str, value: Rc<Template>) {
self.map.insert(key.to_string(), Rc::downgrade(&value));
}
fn remove(&mut self, key: &str) {
self.map.remove(key);
}
fn clear(&mut self) {
self.map.clear();
}
}
impl CacheStorageWithGetSize for SoftCacheStorage {
fn get_size(&mut self) -> usize {
self.map.len()
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::parser;
use crate::template::Configuration;
#[test]
fn weak_semantics() {
let mut s = SoftCacheStorage::default();
let cfg = Rc::new(Configuration::default());
let t = Rc::new(parser::parse(&cfg, "a.ftl", "x").unwrap());
s.put("a.ftl", t.clone());
assert!(s.get("a.ftl").is_some());
drop(t);
assert!(s.get("a.ftl").is_none());
}
}