1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
use crate::Fail;
use std::collections::BTreeMap;
use std::fs::File;
use std::io::prelude::Read;
use std::str::FromStr;
#[derive(Clone, Debug)]
pub struct Config<'a> {
conf: BTreeMap<&'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) -> &BTreeMap<&str, &str> {
&self.conf
}
pub fn read(path: &str, buf: &'a mut String) -> Result<Self, Fail> {
let mut file = File::open(path).or_else(Fail::from)?;
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 = BTreeMap::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 }
}
}