1use config::{ConfigError, FileStoredFormat, Format, Map, Value, ValueKind};
4use std::error::Error;
6#[derive(Debug, Clone)]
9pub struct MyTomlFile;
10
11impl Format for MyTomlFile {
12 fn parse(&self, uri: Option<&String>, text: &str) -> Result<Map<String, Value>, Box<dyn Error + Send + Sync>> {
13 let value = from_toml_value(uri, &toml::from_str(text)?);
14
15 match value.kind {
18 ValueKind::Table(map) => Ok(map),
19 _ => Err(ConfigError::Message("The config is not a table".to_string())),
20 }
21 .map_err(|err| Box::new(err) as Box<dyn Error + Send + Sync>)
22 }
23}
24impl FileStoredFormat for MyTomlFile {
27 fn file_extensions(&self) -> &'static [&'static str] {
28 &["toml"]
29 }
30}
31
32fn from_toml_value(uri: Option<&String>, value: &toml::Value) -> Value {
36 match *value {
37 toml::Value::String(ref value) => {
38 if value.to_string().to_lowercase() == "auto" {
39 Value::new(uri, ValueKind::Nil)
40 } else {
41 Value::new(uri, value.to_string())
42 }
43 }
44 toml::Value::Float(value) => Value::new(uri, value),
45 toml::Value::Integer(value) => Value::new(uri, value),
46 toml::Value::Boolean(value) => Value::new(uri, value),
47
48 toml::Value::Table(ref table) => {
49 let mut m = Map::new();
50
51 for (key, value) in table {
52 m.insert(key.clone(), from_toml_value(uri, value));
53 }
54
55 Value::new(uri, m)
56 }
57
58 toml::Value::Array(ref array) => {
59 let mut l = Vec::new();
60
61 for value in array {
62 l.push(from_toml_value(uri, value));
63 }
64
65 Value::new(uri, l)
66 }
67
68 toml::Value::Datetime(ref datetime) => Value::new(uri, datetime.to_string()),
69 }
70}