comparison rust/src/config.rs @ 601:8c21df3711e2 rust

rigid_config more on sensors
author Matt Johnston <matt@ucc.asn.au>
date Wed, 15 Feb 2017 23:58:02 +0800
parents 9c76f3cf01ea
children f3e39e2107fd
comparison
equal deleted inserted replaced
600:9c76f3cf01ea 601:8c21df3711e2
1 extern crate toml; 1 extern crate toml;
2 2
3 use std::error::Error;
3 use std::fs::File; 4 use std::fs::File;
4 use std::io::Read; 5 use std::io::Read;
5 use serde::{Serialize,Deserialize,Deserializer,Serializer}; 6 use serde::{Serialize,Deserialize,Deserializer,Serializer};
6 7
7 #[derive(Deserialize,Serialize,Debug,Clone)] 8 #[derive(Deserialize,Serialize,Debug,Clone)]
66 67
67 pub fn to_toml_string(&self) -> String { 68 pub fn to_toml_string(&self) -> String {
68 toml::to_string(self).unwrap() 69 toml::to_string(self).unwrap()
69 } 70 }
70 71
71 pub fn merge(&self, conf: &str) -> Result<Self, String>{ 72 pub fn merge(&self, conf: &str) -> Result<Self, Box<Error>> {
72 // convert existing and new toml into tables, combine them. 73 // convert existing and new toml into tables, combine them.
73 let mut new_toml = try!(toml::from_str(conf).map_err(|e| e.to_string())); 74 let mut new_toml = toml::from_str(conf)?;
74 let mut ex_val = toml::Value::try_from(self).unwrap(); 75 let mut ex_val = toml::Value::try_from(self).unwrap();
75 let mut ex_toml = ex_val.as_table_mut().unwrap(); 76 let mut ex_toml = ex_val.as_table_mut().unwrap();
76 ex_toml.append(&mut new_toml); 77 ex_toml.append(&mut new_toml);
77 let ret: Self = toml::Value::Table(ex_toml.clone()).try_into().unwrap(); 78 // TODO: wrap the error with a better message?
79 let ret = toml::Value::Table(ex_toml.clone()).try_into()?;
78 Ok(ret) 80 Ok(ret)
79 } 81 }
80 82
81 pub fn merge_file(&self, filename: &str) -> Result<Self, String>{ 83 pub fn merge_file(&self, filename: &str) -> Result<Self, Box<Error>> {
82 84
83 let r = File::open(filename) 85 let mut s = String::new();
84 .and_then(|mut f| { 86 File::open(filename)?.read_to_string(&mut s)?;
85 let mut s = String::new();
86 f.read_to_string(&mut s)
87 .map(|_| s)
88 })
89 .map_err(|e| e.to_string());
90 87
91 r.and_then(|s| { 88 self.merge(&s)
92 self.merge(&s)
93 })
94 .map_err(|e| {
95 format!("Error loading config file {}: {}",
96 filename, e)
97 })
98 } 89 }
99 } 90 }