aboutsummaryrefslogtreecommitdiff
path: root/examples
diff options
context:
space:
mode:
authorErick Tryzelaar <erick.tryzelaar@gmail.com>2015-08-12 22:15:58 -0700
committerErick Tryzelaar <erick.tryzelaar@gmail.com>2015-08-12 22:15:58 -0700
commit4e0172a9a510bdd4468dc22c562d79c3c5449daa (patch)
tree79ad2f9d42851e047c67b4495216b0f103f2902c /examples
parentfac884d032526a25eb26db54047c62a21945aaf4 (diff)
parentb70f6e53b20c8f90f525219b1db7e99f6ef417dc (diff)
downloadmilf-rs-4e0172a9a510bdd4468dc22c562d79c3c5449daa.tar.gz
milf-rs-4e0172a9a510bdd4468dc22c562d79c3c5449daa.zip
Merge remote-tracking branch 'remotes/origin/master' into serde
Diffstat (limited to 'examples')
-rw-r--r--examples/toml2json.rs57
1 files changed, 57 insertions, 0 deletions
diff --git a/examples/toml2json.rs b/examples/toml2json.rs
new file mode 100644
index 0000000..0d40680
--- /dev/null
+++ b/examples/toml2json.rs
@@ -0,0 +1,57 @@
+#![deny(warnings)]
+
+extern crate toml;
+extern crate rustc_serialize;
+
+use std::fs::File;
+use std::env;
+use std::io;
+use std::io::prelude::*;
+
+use toml::Value;
+use rustc_serialize::json::Json;
+
+fn main() {
+ let mut args = env::args();
+ let mut input = String::new();
+ let filename = if args.len() > 1 {
+ let name = args.nth(1).unwrap();
+ File::open(&name).and_then(|mut f| {
+ f.read_to_string(&mut input)
+ }).unwrap();
+ name
+ } else {
+ io::stdin().read_to_string(&mut input).unwrap();
+ "<stdin>".to_string()
+ };
+
+ let mut parser = toml::Parser::new(&input);
+ let toml = match parser.parse() {
+ Some(toml) => toml,
+ None => {
+ for err in &parser.errors {
+ let (loline, locol) = parser.to_linecol(err.lo);
+ let (hiline, hicol) = parser.to_linecol(err.hi);
+ println!("{}:{}:{}-{}:{} error: {}",
+ filename, loline, locol, hiline, hicol, err.desc);
+ }
+ return
+ }
+ };
+ let json = convert(Value::Table(toml));
+ println!("{}", json.pretty());
+}
+
+fn convert(toml: Value) -> Json {
+ match toml {
+ Value::String(s) => Json::String(s),
+ Value::Integer(i) => Json::I64(i),
+ Value::Float(f) => Json::F64(f),
+ Value::Boolean(b) => Json::Boolean(b),
+ Value::Array(arr) => Json::Array(arr.into_iter().map(convert).collect()),
+ Value::Table(table) => Json::Object(table.into_iter().map(|(k, v)| {
+ (k, convert(v))
+ }).collect()),
+ Value::Datetime(dt) => Json::String(dt),
+ }
+}