use crate::{Fail, Result};
use std::collections::HashMap;
use std::fs::File;
use std::io::prelude::Read;
use std::str::FromStr;
#[derive(Clone, Debug)]
pub struct Config<'a> {
conf: HashMap<&'a str, &'a str>,
}
impl<'a> Config<'a> {
pub fn get<T: FromStr>(&self, name: &str, default: T) -> T {
match self.conf.get(name) {
Some(value) => value.parse().unwrap_or(default),
None => default,
}
}
pub fn value(&self, name: &str, default: &'a str) -> &str {
match self.conf.get(name) {
Some(value) => value,
None => default,
}
}
pub fn exists(&self, name: &str) -> bool {
self.conf.contains_key(name)
}
pub fn conf(&self) -> &HashMap<&str, &str> {
&self.conf
}
pub fn read(path: &str, buf: &'a mut String) -> Result<Self> {
let mut file = File::open(path)?;
match file.read_to_string(buf) {
Ok(_) => Ok(Self::from(buf)),
Err(err) => Fail::from(err),
}
}
pub fn from(raw: &'a str) -> Self {
let mut conf = HashMap::new();
raw.split('\n')
.map(|l| l.splitn(2, '=').map(|c| c.trim()).collect())
.for_each(|kv: Vec<&str>| {
if kv.len() == 2 {
conf.insert(kv[0], kv[1]);
}
});
Self { conf }
}
}