comparison rust/src/config.rs @ 600:9c76f3cf01ea rust

slightly less ugly
author Matt Johnston <matt@ucc.asn.au>
date Tue, 07 Feb 2017 22:57:29 +0800
parents f71cf1ad745f
children 8c21df3711e2
comparison
equal deleted inserted replaced
599:f71cf1ad745f 600:9c76f3cf01ea
66 66
67 pub fn to_toml_string(&self) -> String { 67 pub fn to_toml_string(&self) -> String {
68 toml::to_string(self).unwrap() 68 toml::to_string(self).unwrap()
69 } 69 }
70 70
71
72 pub fn merge(&self, conf: &str) -> Result<Self, String>{ 71 pub fn merge(&self, conf: &str) -> Result<Self, String>{
73 println!("config {}", conf); 72 // convert existing and new toml into tables, combine them.
74 let mut new_toml = try!(toml::from_str(conf).map_err(|e| e.to_string())); 73 let mut new_toml = try!(toml::from_str(conf).map_err(|e| e.to_string()));
75 let mut ex_val = toml::Value::try_from(self).unwrap(); 74 let mut ex_val = toml::Value::try_from(self).unwrap();
76 let mut ex_toml = ex_val.as_table_mut().unwrap(); 75 let mut ex_toml = ex_val.as_table_mut().unwrap();
77 ex_toml.append(&mut new_toml); 76 ex_toml.append(&mut new_toml);
78 let ret: Self = toml::Value::Table(ex_toml.clone()).try_into().unwrap(); 77 let ret: Self = toml::Value::Table(ex_toml.clone()).try_into().unwrap();
79 return Ok(ret) 78 Ok(ret)
80
81
82 /*
83 let mut p = toml::Parser::new(&conf);
84 let p =
85 p.parse()
86 .ok_or_else(|| {
87 format!("toml parsing failed: {:?}", p.errors)
88 })
89 .map(|mut new_toml| {
90 let mut e = toml::Encoder::new();
91 self.serialize(&mut e).unwrap(); // XXX what could go wrong?
92 let mut ex_toml = e.toml;
93 ex_toml.append(&mut new_toml);
94 let mut dec = toml::Decoder::new(toml::Value::Table(ex_toml));
95 Self::deserialize(&mut dec).unwrap() // could this go wrong?
96 })
97 */
98 } 79 }
99 80
100 pub fn merge_file(&self, filename: &str) -> Result<Self, String>{ 81 pub fn merge_file(&self, filename: &str) -> Result<Self, String>{
101 82
102 let r = File::open(filename) 83 let r = File::open(filename)
103 .map_err(|e| e.to_string())
104 .and_then(|mut f| { 84 .and_then(|mut f| {
105 let mut s = String::new(); 85 let mut s = String::new();
106 f.read_to_string(&mut s) 86 f.read_to_string(&mut s)
107 .map_err(|e| e.to_string())
108 .map(|_| s) 87 .map(|_| s)
109 }); 88 })
89 .map_err(|e| e.to_string());
110 90
111 r.and_then(|s| { 91 r.and_then(|s| {
112 self.merge(&s) 92 self.merge(&s)
113 }) 93 })
114 .map_err(|e| { 94 .map_err(|e| {