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
70
71
//! Configuration utilities

use crate::{Fail, Result};
use std::collections::HashMap;
use std::fs::File;
use std::io::prelude::Read;
use std::str::FromStr;

/// Configuration file parser
#[derive(Clone, Debug)]
pub struct Config<'a> {
    conf: HashMap<&'a str, &'a str>,
}

impl<'a> Config<'a> {
    /// Get parsed value from config or default
    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,
        }
    }

    /// Get &str value from config or default
    pub fn value(&self, name: &str, default: &'a str) -> &str {
        match self.conf.get(name) {
            Some(value) => value,
            None => default,
        }
    }

    /// Check whether key exists in config
    pub fn exists(&self, name: &str) -> bool {
        self.conf.contains_key(name)
    }

    /// Get config key/value map
    pub fn conf(&self) -> &HashMap<&str, &str> {
        &self.conf
    }

    /// Read config from file
    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),
        }
    }

    /// Create new config from raw config string
    pub fn from(raw: &'a str) -> Self {
        // initialize map
        let mut conf = HashMap::new();

        // split lines
        raw.split('\n')
            // seperate and trim
            .map(|l| l.splitn(2, '=').map(|c| c.trim()).collect())
            // iterate through seperated lines
            .for_each(|kv: Vec<&str>| {
                // check if contains key and value
                if kv.len() == 2 {
                    // add to map
                    conf.insert(kv[0], kv[1]);
                }
            });

        Self { conf }
    }
}