Skip to content

Commit 9b0aa73

Browse files
committed
Bootstrap solution
1 parent 2502fbc commit 9b0aa73

File tree

2 files changed

+64
-1
lines changed

2 files changed

+64
-1
lines changed

src/config.rs

Lines changed: 28 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -129,6 +129,25 @@ impl Config {
129129
self.refresh()
130130
}
131131

132+
pub fn set_defaults<T>(&mut self, value: &T) -> Result<&mut Config>
133+
where
134+
T: Serialize,
135+
{
136+
match self.kind {
137+
ConfigKind::Mutable {
138+
ref mut defaults, ..
139+
} => {
140+
for (key, val) in Self::try_from(&value)?.collect()? {
141+
defaults.insert(key.parse()?, val);
142+
}
143+
}
144+
145+
ConfigKind::Frozen => return Err(ConfigError::Frozen),
146+
}
147+
148+
self.refresh()
149+
}
150+
132151
pub fn set<T>(&mut self, key: &str, value: T) -> Result<&mut Config>
133152
where
134153
T: Into<Value>,
@@ -192,13 +211,21 @@ impl Config {
192211
T::deserialize(self)
193212
}
194213

195-
/// Attempt to deserialize the entire configuration into the requested type.
214+
/// Attempt to serialize the entire configuration from the given type.
196215
pub fn try_from<T: Serialize>(from: &T) -> Result<Self> {
197216
let mut serializer = ConfigSerializer::default();
198217
from.serialize(&mut serializer)?;
199218
Ok(serializer.output)
200219
}
201220

221+
/// Attempt to serialize the entire configuration from the given type
222+
/// as default values.
223+
pub fn try_defaults_from<T: Serialize>(from: &T) -> Result<Self> {
224+
let mut c = Self::new();
225+
c.set_defaults(from)?;
226+
Ok(c)
227+
}
228+
202229
#[deprecated(since = "0.7.0", note = "please use 'try_into' instead")]
203230
pub fn deserialize<'de, T: Deserialize<'de>>(self) -> Result<T> {
204231
self.try_into()

tests/defaults.rs

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
extern crate config;
2+
3+
#[macro_use]
4+
extern crate serde_derive;
5+
6+
use config::*;
7+
8+
#[derive(Debug, Serialize, Deserialize)]
9+
pub struct Settings {
10+
pub db_host: String,
11+
}
12+
13+
impl Default for Settings {
14+
fn default() -> Self {
15+
Settings {
16+
db_host: String::from("default"),
17+
}
18+
}
19+
}
20+
21+
#[test]
22+
fn set_defaults() {
23+
let mut c = Config::new();
24+
c.set_defaults(&Settings::default())
25+
.expect("Setting defaults failed");
26+
let s: Settings = c.try_into().expect("Deserialization failed");
27+
28+
assert_eq!(s.db_host, "default");
29+
}
30+
31+
#[test]
32+
fn try_from_defaults() {
33+
let c = Config::try_from(&Settings::default()).expect("Serialization failed");
34+
let s: Settings = c.try_into().expect("Deserialization failed");
35+
assert_eq!(s.db_host, "default");
36+
}

0 commit comments

Comments
 (0)