File tree Expand file tree Collapse file tree 2 files changed +64
-1
lines changed Expand file tree Collapse file tree 2 files changed +64
-1
lines changed Original file line number Diff line number Diff line change @@ -129,6 +129,25 @@ impl Config {
129
129
self . refresh ( )
130
130
}
131
131
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
+
132
151
pub fn set < T > ( & mut self , key : & str , value : T ) -> Result < & mut Config >
133
152
where
134
153
T : Into < Value > ,
@@ -192,13 +211,21 @@ impl Config {
192
211
T :: deserialize ( self )
193
212
}
194
213
195
- /// Attempt to deserialize the entire configuration into the requested type.
214
+ /// Attempt to serialize the entire configuration from the given type.
196
215
pub fn try_from < T : Serialize > ( from : & T ) -> Result < Self > {
197
216
let mut serializer = ConfigSerializer :: default ( ) ;
198
217
from. serialize ( & mut serializer) ?;
199
218
Ok ( serializer. output )
200
219
}
201
220
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
+
202
229
#[ deprecated( since = "0.7.0" , note = "please use 'try_into' instead" ) ]
203
230
pub fn deserialize < ' de , T : Deserialize < ' de > > ( self ) -> Result < T > {
204
231
self . try_into ( )
Original file line number Diff line number Diff line change
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
+ }
You can’t perform that action at this time.
0 commit comments