use errors::*;
use fs2::FileExt;
use regex::Regex;
use std::error::Error;
use std::fs::{create_dir_all, read_dir, remove_file, File};
use std::io::prelude::*;
use std::path::Path;
use PersistentCache;
#[allow(unused_imports)]
use PREFIX;
pub struct FileStorage {
path: String,
}
impl FileStorage {
pub fn new(path: &str) -> Result<Self> {
create_dir_all(path)?;
Ok(FileStorage {
path: path.to_owned(),
})
}
}
impl PersistentCache for FileStorage {
fn get(&mut self, name: &str) -> Result<Vec<u8>> {
let fpath = format!("{}/{}", self.path, name);
let p = Path::new(&fpath);
let mut file = match File::open(&p) {
Err(_) => return Ok(vec![]),
Ok(f) => f,
};
file.lock_exclusive()?;
let mut s: Vec<u8> = Vec::new();
match file.read_to_end(&mut s) {
Ok(_) => {
file.unlock()?;
Ok(s.to_vec())
}
Err(e) => {
file.unlock()?;
Err(e.into())
}
}
}
fn set(&mut self, name: &str, val: &[u8]) -> Result<()> {
let fpath = format!("{}/{}", self.path, name);
let p = Path::new(&fpath);
let mut file = match File::create(&p) {
Err(e) => return Err(e.into()),
Ok(f) => f,
};
file.lock_exclusive()?;
file.write_all(val)?;
file.unlock()?;
Ok(())
}
fn flush(&mut self) -> Result<()> {
let p = Path::new(&self.path);
match read_dir(p) {
Err(e) => return Err(e.into()),
Ok(iterator) => {
let re = Regex::new(&format!(r"^{}/{}_", self.path, PREFIX))?;
for file in iterator {
let tmp = file?.path();
let f = tmp.to_str().unwrap();
if re.is_match(f) {
remove_file(f)?
}
}
}
}
Ok(())
}
}