summaryrefslogtreecommitdiffstats
path: root/src/file/toml.rs
blob: e3fb0d82bc0de4f47886760a0f419a30d880c1da (plain)
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
72
73
74
use toml;
use source::Source;
use std::collections::{HashMap, BTreeMap};
use std::error::Error;
use value::Value;

pub struct Content {
    // Root table of the TOML document
    root: toml::Value,
}

impl Content {
    pub fn parse(text: &str, namespace: Option<&String>) -> Result<Box<Source>, Box<Error>> {
        // Parse
        let mut parser = toml::Parser::new(text);
        // TODO: Get a solution to make this return an Error-able
        let mut root = parser.parse().unwrap();

        // Limit to namespace
        if let Some(namespace) = namespace {
            if let Some(toml::Value::Table(table)) = root.remove(namespace) {
                root = table;
            } else {
                // TODO: Warn?
                root = BTreeMap::new();
            }
        }

        Ok(Box::new(Content { root: toml::Value::Table(root) }))
    }
}

fn from_toml_value(value: &toml::Value) -> Value {
    match *value {
        toml::Value::String(ref value) => Value::String(value.clone()),
        toml::Value::Float(value) => Value::Float(value),
        toml::Value::Integer(value) => Value::Integer(value),
        toml::Value::Boolean(value) => Value::Boolean(value),

        toml::Value::Table(ref table) => {
            let mut m = HashMap::new();

            for (key, value) in table {
                m.insert(key.clone(), from_toml_value(value));
            }

            Value::Table(m)
        }

        toml::Value::Array(ref array) => {
            let mut l = Vec::new();

            for value in array {
                l.push(from_toml_value(value));
            }

            Value::Array(l)
        }

        _ => {
            unimplemented!();
        }
    }
}

impl Source for Content {
    fn collect(&self) -> HashMap<String, Value> {
        if let Value::Table(table) = from_toml_value(&self.root) {
            table
        } else {
            unreachable!();
        }
    }
}