summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authortyranron <tyranron@gmail.com>2019-04-08 15:11:55 +0300
committertyranron <tyranron@gmail.com>2019-04-08 15:11:55 +0300
commit9b0aa7362c21b01376739a013126a9db3ce355bc (patch)
tree204f64501f2ca2b261abd431401481ad88a8556b
parent2502fbcce7295c56efd9825a14748d98f76ef613 (diff)
Bootstrap solution
-rw-r--r--src/config.rs29
-rw-r--r--tests/defaults.rs36
2 files changed, 64 insertions, 1 deletions
diff --git a/src/config.rs b/src/config.rs
index f19e59a..893baea 100644
--- a/src/config.rs
+++ b/src/config.rs
@@ -129,6 +129,25 @@ impl Config {
self.refresh()
}
+ pub fn set_defaults<T>(&mut self, value: &T) -> Result<&mut Config>
+ where
+ T: Serialize,
+ {
+ match self.kind {
+ ConfigKind::Mutable {
+ ref mut defaults, ..
+ } => {
+ for (key, val) in Self::try_from(&value)?.collect()? {
+ defaults.insert(key.parse()?, val);
+ }
+ }
+
+ ConfigKind::Frozen => return Err(ConfigError::Frozen),
+ }
+
+ self.refresh()
+ }
+
pub fn set<T>(&mut self, key: &str, value: T) -> Result<&mut Config>
where
T: Into<Value>,
@@ -192,13 +211,21 @@ impl Config {
T::deserialize(self)
}
- /// Attempt to deserialize the entire configuration into the requested type.
+ /// Attempt to serialize the entire configuration from the given type.
pub fn try_from<T: Serialize>(from: &T) -> Result<Self> {
let mut serializer = ConfigSerializer::default();
from.serialize(&mut serializer)?;
Ok(serializer.output)
}
+ /// Attempt to serialize the entire configuration from the given type
+ /// as default values.
+ pub fn try_defaults_from<T: Serialize>(from: &T) -> Result<Self> {
+ let mut c = Self::new();
+ c.set_defaults(from)?;
+ Ok(c)
+ }
+
#[deprecated(since = "0.7.0", note = "please use 'try_into' instead")]
pub fn deserialize<'de, T: Deserialize<'de>>(self) -> Result<T> {
self.try_into()
diff --git a/tests/defaults.rs b/tests/defaults.rs
new file mode 100644
index 0000000..b00da29
--- /dev/null
+++ b/tests/defaults.rs
@@ -0,0 +1,36 @@
+extern crate config;
+
+#[macro_use]
+extern crate serde_derive;
+
+use config::*;
+
+#[derive(Debug, Serialize, Deserialize)]
+pub struct Settings {
+ pub db_host: String,
+}
+
+impl Default for Settings {
+ fn default() -> Self {
+ Settings {
+ db_host: String::from("default"),
+ }
+ }
+}
+
+#[test]
+fn set_defaults() {
+ let mut c = Config::new();
+ c.set_defaults(&Settings::default())
+ .expect("Setting defaults failed");
+ let s: Settings = c.try_into().expect("Deserialization failed");
+
+ assert_eq!(s.db_host, "default");
+}
+
+#[test]
+fn try_from_defaults() {
+ let c = Config::try_from(&Settings::default()).expect("Serialization failed");
+ let s: Settings = c.try_into().expect("Deserialization failed");
+ assert_eq!(s.db_host, "default");
+}