How to create a TOML file from Rust? -
i have collected data vector , need create toml file data. have managed create , open file:
let mut file = try!(file::create("servers.toml"));
my vector<(string,(string, u32))>
contains following data, should in toml.
[server.a] ipaddr="192.168.4.1" port no=4476 [server.b] ......
i have lot of data needs written in toml , know toml text file. how encoder used for?
this uses toml crate structure , serialization. main benefit values should escaped.
extern crate toml; use toml::value; use std::collections::btreemap; use std::io::prelude::*; fn to_toml(v: vec<(string, (string, u32))>) -> value { let mut servers = btreemap::new(); (name, (ip_addr, port)) in v { let mut server = btreemap::new(); server.insert("ipaddr".into(), value::string(ip_addr)); server.insert("port no".into(), value::integer(port i64)); servers.insert(name, value::table(server)); } let mut map = btreemap::new(); map.insert("server".into(), value::table(servers)); value::table(map) } fn main() { let v = vec![("a".into(), ("192.168.4.1".into(), 4476)), ("b".into(), ("192.168.4.8".into(), 1234))]; let toml_string = toml::encode_str(&to_toml(v)); println!("{}", toml_string); let mut file = std::fs::file::create("servers.toml").unwrap(); file.write_all(toml_string.as_bytes()).expect("could not write file!"); }
Comments
Post a Comment