Skip to main content

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/// Helper for `derive_deftly(TorConfig)`: implements ExtendBuilder for a field by replacing
148/// one value with another.
149///
150/// This is the default behavior for non-subbuilder fields.
151pub fn extend_with_replace<T>(cfg: &mut T, value: T, _strategy: ExtendStrategy) {
152    *cfg = value;
153}
154
155#[cfg(test)]
156mod test {
157    // @@ begin test lint list maintained by maint/add_warning @@
158    #![allow(clippy::bool_assert_comparison)]
159    #![allow(clippy::clone_on_copy)]
160    #![allow(clippy::dbg_macro)]
161    #![allow(clippy::mixed_attributes_style)]
162    #![allow(clippy::print_stderr)]
163    #![allow(clippy::print_stdout)]
164    #![allow(clippy::single_char_pattern)]
165    #![allow(clippy::unwrap_used)]
166    #![allow(clippy::unchecked_time_subtraction)]
167    #![allow(clippy::useless_vec)]
168    #![allow(clippy::needless_pass_by_value)]
169    //! <!-- @@ end test lint list maintained by maint/add_warning @@ -->
170
171    use super::*;
172    use derive_deftly::Deftly;
173
174    #[derive(Clone, Debug, derive_builder::Builder, Eq, PartialEq, Deftly)]
175    #[derive_deftly(ExtendBuilder)]
176    struct Album {
177        title: String,
178        year: u32,
179        #[builder(setter(strip_option), default)]
180        n_volumes: Option<u8>,
181        #[builder(sub_builder)]
182        #[deftly(extend_builder(sub_builder))]
183        artist: Artist,
184    }
185
186    #[derive(Clone, Debug, derive_builder::Builder, Eq, PartialEq, Deftly)]
187    #[derive_deftly(ExtendBuilder)]
188    struct Artist {
189        name: String,
190        #[builder(setter(strip_option), default)]
191        year_formed: Option<u32>,
192    }
193
194    #[test]
195    fn extend() {
196        let mut a = AlbumBuilder::default();
197        a.artist().year_formed(1940);
198        a.title("Untitled".to_string());
199
200        let mut b = AlbumBuilder::default();
201        b.year(1980).artist().name("Unknown artist".to_string());
202        let mut aa = a.clone();
203        aa.extend_from(b, ExtendStrategy::ReplaceLists);
204        let aa = aa.build().unwrap();
205        assert_eq!(
206            aa,
207            Album {
208                title: "Untitled".to_string(),
209                year: 1980,
210                n_volumes: None,
211                artist: Artist {
212                    name: "Unknown artist".to_string(),
213                    year_formed: Some(1940)
214                }
215            }
216        );
217
218        let mut b = AlbumBuilder::default();
219        b.year(1969)
220            .title("Hot Rats".to_string())
221            .artist()
222            .name("Frank Zappa".into());
223        let mut aa = a.clone();
224        aa.extend_from(b, ExtendStrategy::ReplaceLists);
225        let aa = aa.build().unwrap();
226        assert_eq!(
227            aa,
228            Album {
229                title: "Hot Rats".to_string(),
230                year: 1969,
231                n_volumes: None,
232                artist: Artist {
233                    name: "Frank Zappa".to_string(),
234                    year_formed: Some(1940)
235                }
236            }
237        );
238    }
239
240    #[derive(Clone, Debug, derive_builder::Builder, Eq, PartialEq, Deftly)]
241    #[builder(derive(Debug, Eq, PartialEq))]
242    #[derive_deftly(ExtendBuilder)]
243    struct DAndS {
244        simple: Option<u32>,
245        #[builder(default = "Some(123)")]
246        dflt: Option<u32>,
247        #[builder(setter(strip_option))]
248        strip: Option<u32>,
249        #[builder(setter(strip_option), default = "Some(456)")]
250        strip_dflt: Option<u32>,
251    }
252    // For reference, the above will crate code something like the example below.
253    // (This may help the tests make more sense)
254    /*
255    #[derive(Default)]
256    struct DAndSBuilder {
257        simple: Option<Option<u32>>,
258        dflt: Option<Option<u32>>,
259        strip: Option<Option<u32>>,
260        strip_dflt: Option<Option<u32>>,
261    }
262    #[allow(unused)]
263    impl DAndSBuilder {
264        fn simple(&mut self, val: Option<u32>) -> &mut Self {
265            self.simple = Some(val);
266            self
267        }
268        fn dflt(&mut self, val: Option<u32>) -> &mut Self {
269            self.dflt = Some(val);
270            self
271        }
272        fn strip(&mut self, val: u32) -> &mut Self {
273            self.strip = Some(Some(val));
274            self
275        }
276        fn strip_dflt(&mut self, val: u32) -> &mut Self {
277            self.strip = Some(Some(val));
278            self
279        }
280        fn build(&self) -> Result<DAndS, DAndSBuilderError> {
281            Ok(DAndS {
282                simple: self
283                    .simple
284                    .ok_or(DAndSBuilderError::UninitializedField("simple"))?,
285                dflt: self.simple.unwrap_or(Some(123)),
286                strip: self
287                    .strip
288                    .ok_or(DAndSBuilderError::UninitializedField("strip"))?,
289                strip_dflt: self.simple.unwrap_or(Some(456)),
290            })
291        }
292    }
293    */
294
295    #[test]
296    // Demonstrate "default" and "strip_option" behavior without Extend.
297    fn default_and_strip_noextend() {
298        // Didn't set non-default options; this will fail.
299        assert!(DAndSBuilder::default().build().is_err());
300        assert!(DAndSBuilder::default().simple(Some(7)).build().is_err());
301        assert!(DAndSBuilder::default().strip(7).build().is_err());
302
303        // We can get away with setting only the non-defaulting options.
304        let v = DAndSBuilder::default()
305            .simple(Some(7))
306            .strip(77)
307            .build()
308            .unwrap();
309        assert_eq!(
310            v,
311            DAndS {
312                simple: Some(7),
313                dflt: Some(123),
314                strip: Some(77),
315                strip_dflt: Some(456)
316            }
317        );
318
319        // But we _can_ also set the defaulting options.
320        let v = DAndSBuilder::default()
321            .simple(Some(7))
322            .strip(77)
323            .dflt(Some(777))
324            .strip_dflt(7777)
325            .build()
326            .unwrap();
327        assert_eq!(
328            v,
329            DAndS {
330                simple: Some(7),
331                dflt: Some(777),
332                strip: Some(77),
333                strip_dflt: Some(7777)
334            }
335        );
336
337        // Now inspect the state of an uninitialized builder, and verify that it works as expected.
338        //
339        // Notably, everything is an Option<Option<...>> for this builder:
340        // `strip_option` only affects the behavior of the setter function,
341        // and `default` only affects the behavior of the build function.
342        // Neither affects the representation..
343        let mut bld = DAndSBuilder::default();
344        assert_eq!(
345            bld,
346            DAndSBuilder {
347                simple: None,
348                dflt: None,
349                strip: None,
350                strip_dflt: None
351            }
352        );
353        bld.simple(Some(7))
354            .strip(77)
355            .dflt(Some(777))
356            .strip_dflt(7777);
357        assert_eq!(
358            bld,
359            DAndSBuilder {
360                simple: Some(Some(7)),
361                dflt: Some(Some(777)),
362                strip: Some(Some(77)),
363                strip_dflt: Some(Some(7777)),
364            }
365        );
366    }
367
368    #[test]
369    fn default_and_strip_extending() {
370        fn combine_and_build(
371            b1: &DAndSBuilder,
372            b2: &DAndSBuilder,
373        ) -> Result<DAndS, DAndSBuilderError> {
374            let mut b = b1.clone();
375            b.extend_from(b2.clone(), ExtendStrategy::ReplaceLists);
376            b.build()
377        }
378
379        // We fail if neither builder sets some non-defaulting option.
380        let dflt_builder = DAndSBuilder::default();
381        assert!(combine_and_build(&dflt_builder, &dflt_builder).is_err());
382        let mut simple_only = DAndSBuilder::default();
383        simple_only.simple(Some(7));
384        let mut strip_only = DAndSBuilder::default();
385        strip_only.strip(77);
386        assert!(combine_and_build(&dflt_builder, &simple_only).is_err());
387        assert!(combine_and_build(&dflt_builder, &strip_only).is_err());
388        assert!(combine_and_build(&simple_only, &dflt_builder).is_err());
389        assert!(combine_and_build(&strip_only, &dflt_builder).is_err());
390        assert!(combine_and_build(&strip_only, &strip_only).is_err());
391        assert!(combine_and_build(&simple_only, &simple_only).is_err());
392
393        // But if every non-defaulting option is set in some builder, we succeed.
394        let v1 = combine_and_build(&strip_only, &simple_only).unwrap();
395        let v2 = combine_and_build(&simple_only, &strip_only).unwrap();
396        assert_eq!(v1, v2);
397        assert_eq!(
398            v1,
399            DAndS {
400                simple: Some(7),
401                dflt: Some(123),
402                strip: Some(77),
403                strip_dflt: Some(456)
404            }
405        );
406
407        // For every option, in every case: when a.extend(b) happens,
408        // a set option overrides a non-set option.
409        let mut all_set_1 = DAndSBuilder::default();
410        all_set_1
411            .simple(Some(1))
412            .strip(11)
413            .dflt(Some(111))
414            .strip_dflt(1111);
415        let v1 = combine_and_build(&all_set_1, &dflt_builder).unwrap();
416        let v2 = combine_and_build(&dflt_builder, &all_set_1).unwrap();
417        let expected_all_1s = DAndS {
418            simple: Some(1),
419            dflt: Some(111),
420            strip: Some(11),
421            strip_dflt: Some(1111),
422        };
423        assert_eq!(v1, expected_all_1s);
424        assert_eq!(v2, expected_all_1s);
425
426        // For every option, in every case: If the option is set in both cases,
427        // the extended-from option overrides the previous one.
428        let mut all_set_2 = DAndSBuilder::default();
429        all_set_2
430            .simple(Some(2))
431            .strip(22)
432            .dflt(Some(222))
433            .strip_dflt(2222);
434        let v1 = combine_and_build(&all_set_2, &all_set_1).unwrap();
435        let v2 = combine_and_build(&all_set_1, &all_set_2).unwrap();
436        let expected_all_2s = DAndS {
437            simple: Some(2),
438            dflt: Some(222),
439            strip: Some(22),
440            strip_dflt: Some(2222),
441        };
442        assert_eq!(v1, expected_all_1s); // since all_set_1 came last.
443        assert_eq!(v2, expected_all_2s); // since all_set_2 came last.
444    }
445}