use crate::cache::Cache;
use crate::hash::Hash;
use std::fs::{create_dir_all, File};
use std::io::{self, Write};
use std::path::PathBuf;
use wasmer::{DeserializeError, Module, SerializeError, Store};
pub struct FileSystemCache {
path: PathBuf,
ext: Option<String>,
}
impl FileSystemCache {
pub fn new<P: Into<PathBuf>>(path: P) -> io::Result<Self> {
let path: PathBuf = path.into();
if path.exists() {
let metadata = path.metadata()?;
if metadata.is_dir() {
if !metadata.permissions().readonly() {
Ok(Self { path, ext: None })
} else {
Err(io::Error::new(
io::ErrorKind::PermissionDenied,
format!("the supplied path is readonly: {}", path.display()),
))
}
} else {
Err(io::Error::new(
io::ErrorKind::PermissionDenied,
format!(
"the supplied path already points to a file: {}",
path.display()
),
))
}
} else {
create_dir_all(&path)?;
Ok(Self { path, ext: None })
}
}
pub fn set_cache_extension(&mut self, ext: Option<impl ToString>) {
self.ext = ext.map(|ext| ext.to_string());
}
}
impl Cache for FileSystemCache {
type DeserializeError = DeserializeError;
type SerializeError = SerializeError;
unsafe fn load(&self, store: &Store, key: Hash) -> Result<Module, Self::DeserializeError> {
let filename = if let Some(ref ext) = self.ext {
format!("{}.{}", key.to_string(), ext)
} else {
key.to_string()
};
let path = self.path.join(filename);
Module::deserialize_from_file(&store, path)
}
fn store(&mut self, key: Hash, module: &Module) -> Result<(), Self::SerializeError> {
let filename = if let Some(ref ext) = self.ext {
format!("{}.{}", key.to_string(), ext)
} else {
key.to_string()
};
let path = self.path.join(filename);
let mut file = File::create(path)?;
let buffer = module.serialize()?;
file.write_all(&buffer)?;
Ok(())
}
}