use std::path::{Path, PathBuf};
#[derive(Clone, Debug, Eq, PartialEq)]
#[cfg(feature = "host")]
pub enum CacheRefreshReason {
Missing(PathBuf),
Stale,
}
pub fn load_or_refresh_missing_cache<T, Error>(
mut load: impl FnMut() -> Result<T, Error>,
missing_path: impl FnOnce(Error) -> Result<PathBuf, Error>,
refresh: impl FnOnce(&Path) -> Result<(), Error>,
) -> Result<T, Error> {
match load() {
Ok(cached) => Ok(cached),
Err(err) => {
let path = missing_path(err)?;
refresh(&path)?;
load()
}
}
}
#[cfg(feature = "host")]
pub fn load_or_refresh_stale_cache<T, Error>(
mut load: impl FnMut() -> Result<T, Error>,
stale: impl FnOnce(&T) -> bool,
missing_path: impl FnOnce(Error) -> Result<PathBuf, Error>,
refresh: impl FnOnce(CacheRefreshReason) -> Result<(), Error>,
) -> Result<T, Error> {
match load() {
Ok(cached) if !stale(&cached) => Ok(cached),
Ok(_) => {
refresh(CacheRefreshReason::Stale)?;
load()
}
Err(err) => {
let path = missing_path(err)?;
refresh(CacheRefreshReason::Missing(path))?;
load()
}
}
}