use std::sync::Mutex;
pub struct ModelCache<T: Send> {
slot: Mutex<Option<T>>,
}
impl<T: Send> Default for ModelCache<T> {
fn default() -> Self {
Self::new()
}
}
impl<T: Send> ModelCache<T> {
pub const fn new() -> Self {
Self { slot: Mutex::new(None) }
}
pub fn take_or_create<E>(&self, create_fn: impl FnOnce() -> Result<T, E>) -> Result<T, E> {
if let Ok(mut guard) = self.slot.lock()
&& let Some(model) = guard.take()
{
tracing::debug!("Reusing cached model");
return Ok(model);
}
tracing::debug!("Creating new model (cache miss)");
create_fn()
}
pub fn put(&self, model: T) {
if let Ok(mut guard) = self.slot.lock() {
*guard = Some(model);
}
}
pub fn take(&self) -> Option<T> {
self.slot.lock().ok().and_then(|mut guard| guard.take())
}
}