FEATURE: Support including toml documents

This commit is contained in:
Jeremy Wall 2019-02-20 19:43:56 -06:00
parent 8639912567
commit ff54452766
2 changed files with 34 additions and 1 deletions

View File

@ -94,6 +94,7 @@ impl ImporterRegistry {
); );
registry.register("json", Box::new(json::JsonConverter {})); registry.register("json", Box::new(json::JsonConverter {}));
registry.register("yaml", Box::new(yaml::YamlConverter {})); registry.register("yaml", Box::new(yaml::YamlConverter {}));
registry.register("toml", Box::new(toml::TomlConverter {}));
registry registry
} }

View File

@ -14,6 +14,7 @@
use std; use std;
use std::error; use std::error;
use std::error::Error;
use std::io::Write; use std::io::Write;
use std::rc::Rc; use std::rc::Rc;
@ -21,7 +22,7 @@ use simple_error::SimpleError;
use toml; use toml;
use crate::build::Val; use crate::build::Val;
use crate::convert::traits::{ConvertResult, Converter}; use crate::convert::traits::{ConvertResult, Converter, ImportResult, Importer};
pub struct TomlConverter {} pub struct TomlConverter {}
@ -83,6 +84,30 @@ impl TomlConverter {
Ok(toml_val) Ok(toml_val)
} }
fn convert_toml_val(&self, v: &toml::Value) -> std::result::Result<Val, Box<dyn Error>> {
Ok(match v {
toml::Value::String(s) => Val::Str(s.clone()),
toml::Value::Integer(i) => Val::Int(*i),
toml::Value::Float(f) => Val::Float(*f),
toml::Value::Boolean(b) => Val::Boolean(*b),
toml::Value::Array(l) => {
let mut vs = Vec::with_capacity(l.len());
for aval in l {
vs.push(Rc::new(self.convert_toml_val(aval)?));
}
Val::List(vs)
}
toml::Value::Table(m) => {
let mut fs = Vec::with_capacity(m.len());
for (key, value) in m {
fs.push((key.to_string(), Rc::new(self.convert_toml_val(value)?)));
}
Val::Tuple(fs)
}
toml::Value::Datetime(d) => Val::Str(format!("{}", d)),
})
}
fn write(&self, v: &Val, w: &mut Write) -> ConvertResult { fn write(&self, v: &Val, w: &mut Write) -> ConvertResult {
let toml_val = self.convert_value(v)?; let toml_val = self.convert_value(v)?;
let toml_bytes = toml::ser::to_string_pretty(&toml_val)?; let toml_bytes = toml::ser::to_string_pretty(&toml_val)?;
@ -104,3 +129,10 @@ impl Converter for TomlConverter {
"Convert ucg Vals into valid ucg.".to_string() "Convert ucg Vals into valid ucg.".to_string()
} }
} }
impl Importer for TomlConverter {
fn import(&self, bytes: &[u8]) -> ImportResult {
let json_val = toml::from_slice(bytes)?;
Ok(Rc::new(self.convert_toml_val(&json_val)?))
}
}