tor_config/extend_builder.rs
1//! Functionality for merging one config builder into another.
2
3use derive_deftly::define_derive_deftly;
4use std::collections::{BTreeMap, HashMap};
5
6/// A builder that can be extended from another builder.
7pub trait ExtendBuilder {
8 /// Consume `other`, and merge its contents into `self`.
9 ///
10 /// Generally, whenever a field is set in `other`,
11 /// it should replace any corresponding field in `self`.
12 /// Unset fields in `other` should have no effect.
13 ///
14 /// We use this trait to implement map-style configuration options
15 /// that need to have defaults.
16 /// Rather than simply replacing the maps wholesale
17 /// (as would happen with serde defaults ordinarily)
18 /// we use this trait to copy inner options from the provided options over the defaults
19 /// in the most fine-grained manner possible.
20 ///
21 /// ## When `strategy` is [`ExtendStrategy::ReplaceLists`]:
22 ///
23 /// (No other strategies currently exist.)
24 ///
25 /// Every simple option that is set in `other` should be moved into `self`,
26 /// replacing a previous value (if there was one).
27 ///
28 /// Every list option that is set in `other` should be moved into `self`,
29 /// replacing a previous value (if there was one).
30 ///
31 /// Any complex option (one with an internal tree structure) that is set in `other`
32 /// should recursively be extended, replacing each piece of it that is set in other.
33 fn extend_from(&mut self, other: Self, strategy: ExtendStrategy);
34}
35
36/// Strategy for extending one builder with another.
37///
38/// Currently, only one strategy is defined:
39/// this enum exists so that we can define others in the future.
40#[derive(Clone, Debug, Copy, Eq, PartialEq)]
41// We declare this to be an exhaustive enum, since every ExtendBuilder implementation
42// must support every strategy.
43// So if we add a new strategy, that has to be a breaking change in `ExtendBuilder`.
44#[allow(clippy::exhaustive_enums)]
45pub enum ExtendStrategy {
46 /// Replace all simple options (those with no internal structure).
47 ///
48 /// Replace all list options.
49 ///
50 /// Recursively extend all tree options.
51 ReplaceLists,
52}
53
54impl<K: Ord, T: ExtendBuilder> ExtendBuilder for BTreeMap<K, T> {
55 fn extend_from(&mut self, other: Self, strategy: ExtendStrategy) {
56 use std::collections::btree_map::Entry::*;
57 for (other_k, other_v) in other.into_iter() {
58 match self.entry(other_k) {
59 Vacant(vacant_entry) => {
60 vacant_entry.insert(other_v);
61 }
62 Occupied(mut occupied_entry) => {
63 occupied_entry.get_mut().extend_from(other_v, strategy);
64 }
65 }
66 }
67 }
68}
69
70impl<K: std::hash::Hash + Eq, T: ExtendBuilder> ExtendBuilder for HashMap<K, T> {
71 fn extend_from(&mut self, other: Self, strategy: ExtendStrategy) {
72 use std::collections::hash_map::Entry::*;
73 for (other_k, other_v) in other.into_iter() {
74 match self.entry(other_k) {
75 Vacant(vacant_entry) => {
76 vacant_entry.insert(other_v);
77 }
78 Occupied(mut occupied_entry) => {
79 occupied_entry.get_mut().extend_from(other_v, strategy);
80 }
81 }
82 }
83 }
84}
85
86define_derive_deftly! {
87 /// Provide an [`ExtendBuilder`] implementation for a struct's builder.
88 ///
89 /// This template is only sensible when used alongside `#[derive(Builder)]`.
90 ///
91 /// The provided `extend_from` function will behave as:
92 /// * For every non-`sub_builder` field,
93 /// if there is a value set in `other`,
94 /// replace the value in `self` (if any) with that value.
95 /// (Otherwise, leave the value in `self` as it is).
96 /// * For every `sub_builder` field,
97 /// recursively use `extend_from` to extend that builder
98 /// from the corresponding builder in `other`.
99 ///
100 /// # Interaction with `sub_builder`.
101 ///
102 /// When a field in the struct is tagged with `#[builder(sub_builder)]`,
103 /// you must also tag the same field with `#[deftly(extend_builder(sub_builder))]`;
104 /// otherwise, compilation will fail.
105 ///
106 /// # Interaction with `strip_option` and `default`.
107 ///
108 /// **The flags have no special effect on the `ExtendBuilder`, and will work fine.**
109 ///
110 /// (See comments in the code for details about why, and what this means.
111 /// Remember, `builder(default)` is applied when `build()` is called,
112 /// and does not automatically cause an un-set option to count as set.)
113 export ExtendBuilder for struct, expect items:
114
115 impl $crate::extend_builder::ExtendBuilder for $<$ttype Builder> {
116 fn extend_from(&mut self, other: Self, strategy: $crate::extend_builder::ExtendStrategy) {
117 let _ = strategy; // This will be unused when there is no sub-builder.
118 ${for fields {
119
120 ${if fmeta(extend_builder(sub_builder)) {
121 $crate::extend_builder::ExtendBuilder::extend_from(&mut self.$fname, other.$fname, strategy);
122 } else {
123 // Note that we do not need any special handling here for `strip_option` or
124 // `default`.
125 //
126 // Recall that:
127 // * `strip_option` only takes effect in a setter method,
128 // and causes the setter to wrap an additional Some() around its argument.
129 // * `default` takes effect in the build method,
130 // and controls that method's behavior when.
131 //
132 // In both cases, when the built object has a field of type `T`,
133 // the builder will have a corresponding field of type `Option<T>`,
134 // and will represent an un-set field with `None`.
135 // Therefore, since these flags don't effect the representation of a set or un-set field,
136 // our `extend_from` function doesn't need to know about them.
137 if let Some(other_val) = other.$fname {
138 self.$fname = Some(other_val);
139 }
140 }}
141
142 }}
143 }
144 }
145}
146
147#[cfg(test)]
148mod test {
149 // @@ begin test lint list maintained by maint/add_warning @@
150 #![allow(clippy::bool_assert_comparison)]
151 #![allow(clippy::clone_on_copy)]
152 #![allow(clippy::dbg_macro)]
153 #![allow(clippy::mixed_attributes_style)]
154 #![allow(clippy::print_stderr)]
155 #![allow(clippy::print_stdout)]
156 #![allow(clippy::single_char_pattern)]
157 #![allow(clippy::unwrap_used)]
158 #![allow(clippy::unchecked_time_subtraction)]
159 #![allow(clippy::useless_vec)]
160 #![allow(clippy::needless_pass_by_value)]
161 //! <!-- @@ end test lint list maintained by maint/add_warning @@ -->
162
163 use super::*;
164 use derive_deftly::Deftly;
165
166 #[derive(Clone, Debug, derive_builder::Builder, Eq, PartialEq, Deftly)]
167 #[derive_deftly(ExtendBuilder)]
168 struct Album {
169 title: String,
170 year: u32,
171 #[builder(setter(strip_option), default)]
172 n_volumes: Option<u8>,
173 #[builder(sub_builder)]
174 #[deftly(extend_builder(sub_builder))]
175 artist: Artist,
176 }
177
178 #[derive(Clone, Debug, derive_builder::Builder, Eq, PartialEq, Deftly)]
179 #[derive_deftly(ExtendBuilder)]
180 struct Artist {
181 name: String,
182 #[builder(setter(strip_option), default)]
183 year_formed: Option<u32>,
184 }
185
186 #[test]
187 fn extend() {
188 let mut a = AlbumBuilder::default();
189 a.artist().year_formed(1940);
190 a.title("Untitled".to_string());
191
192 let mut b = AlbumBuilder::default();
193 b.year(1980).artist().name("Unknown artist".to_string());
194 let mut aa = a.clone();
195 aa.extend_from(b, ExtendStrategy::ReplaceLists);
196 let aa = aa.build().unwrap();
197 assert_eq!(
198 aa,
199 Album {
200 title: "Untitled".to_string(),
201 year: 1980,
202 n_volumes: None,
203 artist: Artist {
204 name: "Unknown artist".to_string(),
205 year_formed: Some(1940)
206 }
207 }
208 );
209
210 let mut b = AlbumBuilder::default();
211 b.year(1969)
212 .title("Hot Rats".to_string())
213 .artist()
214 .name("Frank Zappa".into());
215 let mut aa = a.clone();
216 aa.extend_from(b, ExtendStrategy::ReplaceLists);
217 let aa = aa.build().unwrap();
218 assert_eq!(
219 aa,
220 Album {
221 title: "Hot Rats".to_string(),
222 year: 1969,
223 n_volumes: None,
224 artist: Artist {
225 name: "Frank Zappa".to_string(),
226 year_formed: Some(1940)
227 }
228 }
229 );
230 }
231
232 #[derive(Clone, Debug, derive_builder::Builder, Eq, PartialEq, Deftly)]
233 #[builder(derive(Debug, Eq, PartialEq))]
234 #[derive_deftly(ExtendBuilder)]
235 struct DAndS {
236 simple: Option<u32>,
237 #[builder(default = "Some(123)")]
238 dflt: Option<u32>,
239 #[builder(setter(strip_option))]
240 strip: Option<u32>,
241 #[builder(setter(strip_option), default = "Some(456)")]
242 strip_dflt: Option<u32>,
243 }
244 // For reference, the above will crate code something like the example below.
245 // (This may help the tests make more sense)
246 /*
247 #[derive(Default)]
248 struct DAndSBuilder {
249 simple: Option<Option<u32>>,
250 dflt: Option<Option<u32>>,
251 strip: Option<Option<u32>>,
252 strip_dflt: Option<Option<u32>>,
253 }
254 #[allow(unused)]
255 impl DAndSBuilder {
256 fn simple(&mut self, val: Option<u32>) -> &mut Self {
257 self.simple = Some(val);
258 self
259 }
260 fn dflt(&mut self, val: Option<u32>) -> &mut Self {
261 self.dflt = Some(val);
262 self
263 }
264 fn strip(&mut self, val: u32) -> &mut Self {
265 self.strip = Some(Some(val));
266 self
267 }
268 fn strip_dflt(&mut self, val: u32) -> &mut Self {
269 self.strip = Some(Some(val));
270 self
271 }
272 fn build(&self) -> Result<DAndS, DAndSBuilderError> {
273 Ok(DAndS {
274 simple: self
275 .simple
276 .ok_or(DAndSBuilderError::UninitializedField("simple"))?,
277 dflt: self.simple.unwrap_or(Some(123)),
278 strip: self
279 .strip
280 .ok_or(DAndSBuilderError::UninitializedField("strip"))?,
281 strip_dflt: self.simple.unwrap_or(Some(456)),
282 })
283 }
284 }
285 */
286
287 #[test]
288 // Demonstrate "default" and "strip_option" behavior without Extend.
289 fn default_and_strip_noextend() {
290 // Didn't set non-default options; this will fail.
291 assert!(DAndSBuilder::default().build().is_err());
292 assert!(DAndSBuilder::default().simple(Some(7)).build().is_err());
293 assert!(DAndSBuilder::default().strip(7).build().is_err());
294
295 // We can get away with setting only the non-defaulting options.
296 let v = DAndSBuilder::default()
297 .simple(Some(7))
298 .strip(77)
299 .build()
300 .unwrap();
301 assert_eq!(
302 v,
303 DAndS {
304 simple: Some(7),
305 dflt: Some(123),
306 strip: Some(77),
307 strip_dflt: Some(456)
308 }
309 );
310
311 // But we _can_ also set the defaulting options.
312 let v = DAndSBuilder::default()
313 .simple(Some(7))
314 .strip(77)
315 .dflt(Some(777))
316 .strip_dflt(7777)
317 .build()
318 .unwrap();
319 assert_eq!(
320 v,
321 DAndS {
322 simple: Some(7),
323 dflt: Some(777),
324 strip: Some(77),
325 strip_dflt: Some(7777)
326 }
327 );
328
329 // Now inspect the state of an uninitialized builder, and verify that it works as expected.
330 //
331 // Notably, everything is an Option<Option<...>> for this builder:
332 // `strip_option` only affects the behavior of the setter function,
333 // and `default` only affects the behavior of the build function.
334 // Neither affects the representation..
335 let mut bld = DAndSBuilder::default();
336 assert_eq!(
337 bld,
338 DAndSBuilder {
339 simple: None,
340 dflt: None,
341 strip: None,
342 strip_dflt: None
343 }
344 );
345 bld.simple(Some(7))
346 .strip(77)
347 .dflt(Some(777))
348 .strip_dflt(7777);
349 assert_eq!(
350 bld,
351 DAndSBuilder {
352 simple: Some(Some(7)),
353 dflt: Some(Some(777)),
354 strip: Some(Some(77)),
355 strip_dflt: Some(Some(7777)),
356 }
357 );
358 }
359
360 #[test]
361 fn default_and_strip_extending() {
362 fn combine_and_build(
363 b1: &DAndSBuilder,
364 b2: &DAndSBuilder,
365 ) -> Result<DAndS, DAndSBuilderError> {
366 let mut b = b1.clone();
367 b.extend_from(b2.clone(), ExtendStrategy::ReplaceLists);
368 b.build()
369 }
370
371 // We fail if neither builder sets some non-defaulting option.
372 let dflt_builder = DAndSBuilder::default();
373 assert!(combine_and_build(&dflt_builder, &dflt_builder).is_err());
374 let mut simple_only = DAndSBuilder::default();
375 simple_only.simple(Some(7));
376 let mut strip_only = DAndSBuilder::default();
377 strip_only.strip(77);
378 assert!(combine_and_build(&dflt_builder, &simple_only).is_err());
379 assert!(combine_and_build(&dflt_builder, &strip_only).is_err());
380 assert!(combine_and_build(&simple_only, &dflt_builder).is_err());
381 assert!(combine_and_build(&strip_only, &dflt_builder).is_err());
382 assert!(combine_and_build(&strip_only, &strip_only).is_err());
383 assert!(combine_and_build(&simple_only, &simple_only).is_err());
384
385 // But if every non-defaulting option is set in some builder, we succeed.
386 let v1 = combine_and_build(&strip_only, &simple_only).unwrap();
387 let v2 = combine_and_build(&simple_only, &strip_only).unwrap();
388 assert_eq!(v1, v2);
389 assert_eq!(
390 v1,
391 DAndS {
392 simple: Some(7),
393 dflt: Some(123),
394 strip: Some(77),
395 strip_dflt: Some(456)
396 }
397 );
398
399 // For every option, in every case: when a.extend(b) happens,
400 // a set option overrides a non-set option.
401 let mut all_set_1 = DAndSBuilder::default();
402 all_set_1
403 .simple(Some(1))
404 .strip(11)
405 .dflt(Some(111))
406 .strip_dflt(1111);
407 let v1 = combine_and_build(&all_set_1, &dflt_builder).unwrap();
408 let v2 = combine_and_build(&dflt_builder, &all_set_1).unwrap();
409 let expected_all_1s = DAndS {
410 simple: Some(1),
411 dflt: Some(111),
412 strip: Some(11),
413 strip_dflt: Some(1111),
414 };
415 assert_eq!(v1, expected_all_1s);
416 assert_eq!(v2, expected_all_1s);
417
418 // For every option, in every case: If the option is set in both cases,
419 // the extended-from option overrides the previous one.
420 let mut all_set_2 = DAndSBuilder::default();
421 all_set_2
422 .simple(Some(2))
423 .strip(22)
424 .dflt(Some(222))
425 .strip_dflt(2222);
426 let v1 = combine_and_build(&all_set_2, &all_set_1).unwrap();
427 let v2 = combine_and_build(&all_set_1, &all_set_2).unwrap();
428 let expected_all_2s = DAndS {
429 simple: Some(2),
430 dflt: Some(222),
431 strip: Some(22),
432 strip_dflt: Some(2222),
433 };
434 assert_eq!(v1, expected_all_1s); // since all_set_1 came last.
435 assert_eq!(v2, expected_all_2s); // since all_set_2 came last.
436 }
437}