use fnv::FnvHashMap;
use std::io;
use std::path;
use std::cell::RefCell;
use std::fs;
#[derive(Debug)]
pub struct DBFile {
path: path::PathBuf,
contents: RefCell<FnvHashMap<String, String>>,
}
impl DBFile {
pub fn new(path: path::PathBuf, preload: bool) -> DBFile {
let db_file = DBFile {
path: path.clone(),
contents: RefCell::new(FnvHashMap::default()),
};
if preload {
db_file.load_file().unwrap_or_else(|_e| {
exit_with_message!(format!(
"Problem accessing {}, could not create database",
path.to_str().unwrap()
));
});
}
db_file
}
pub fn entry(&self, key: &String) -> Option<String> {
let db_is_empty: bool;
{
db_is_empty = self.contents.borrow().is_empty();
}
if db_is_empty {
self.load_file().unwrap_or_else(|_e| {
exit_with_message!(format!(
"Problem accessing {}, could not create database",
self.path.to_str().unwrap()
));
});
}
match self.contents.borrow().get(key) {
Some(value) => Some(value.clone()),
None => None,
}
}
fn load_file(&self) -> Result<(), io::Error> {
let contents = fs::read_to_string(&self.path)?;
for line in contents.lines() {
for (i, char) in line.char_indices() {
if char == '=' {
let key = line[0..i].trim();
let value = line[i + 1..].trim();
self.contents
.borrow_mut()
.insert(key.to_owned(), value.to_owned());
break;
}
}
}
Ok(())
}
}