| 1 |
#![deny(warnings)] |
| 2 |
|
| 3 |
use std::env; |
| 4 |
use std::fs::File; |
| 5 |
use std::io; |
| 6 |
use std::io::prelude::*; |
| 7 |
|
| 8 |
use serde_json::Value as Json; |
| 9 |
use toml::Value as Toml; |
| 10 |
|
| 11 |
fn main() { |
| 12 |
let mut args = env::args(); |
| 13 |
let mut input = String::new(); |
| 14 |
if args.len() > 1 { |
| 15 |
let name = args.nth(1).unwrap(); |
| 16 |
File::open(&name) |
| 17 |
.and_then(|mut f| f.read_to_string(&mut input)) |
| 18 |
.unwrap(); |
| 19 |
} else { |
| 20 |
io::stdin().read_to_string(&mut input).unwrap(); |
| 21 |
} |
| 22 |
|
| 23 |
match input.parse() { |
| 24 |
Ok(toml) => { |
| 25 |
let json = convert(toml); |
| 26 |
println!("{}", serde_json::to_string_pretty(&json).unwrap()); |
| 27 |
} |
| 28 |
Err(error) => println!("failed to parse TOML: {}", error), |
| 29 |
} |
| 30 |
} |
| 31 |
|
| 32 |
fn convert(toml: Toml) -> Json { |
| 33 |
match toml { |
| 34 |
Toml::String(s) => Json::String(s), |
| 35 |
Toml::Integer(i) => Json::Number(i.into()), |
| 36 |
Toml::Float(f) => { |
| 37 |
let n = serde_json::Number::from_f64(f).expect("float infinite and nan not allowed"); |
| 38 |
Json::Number(n) |
| 39 |
} |
| 40 |
Toml::Boolean(b) => Json::Bool(b), |
| 41 |
Toml::Array(arr) => Json::Array(arr.into_iter().map(convert).collect()), |
| 42 |
Toml::Table(table) => { |
| 43 |
Json::Object(table.into_iter().map(|(k, v)| (k, convert(v))).collect()) |
| 44 |
} |
| 45 |
Toml::Datetime(dt) => Json::String(dt.to_string()), |
| 46 |
} |
| 47 |
} |