merge2 0.3.2

Merge structs into single by values
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
//! Provides [`Merge`][] trait that can be used to merge structs into single by it's values:
//!
//! ```
//! trait Merge: Sized {
//!     fn merge(&mut self, other: &mut Self);
//! }
//! ```
//!
//! # Usage
//!
//! The [`Merge`][] trait can be used to merge two structs into single by values. The example
//! use case is merging configuration from different sources: environment variables,
//! multiple configuration files and command-line arguments, see the [`args.rs`][] example.
//!
//! `Merge` can be derived for structs. Also you can provide custom merge strategies
//! for any fields that don’t implement `Merge` trait.
//! A merge strategy is a function with the signature `fn merge<T>(left: &mut T, right: &mut T)`
//! that merges `right` into `left`. The submodules of this crate provide strategies for the
//! most common types, but you can also define your own strategies.
//!
//! ## Features
//!
//! This crate has the following features:
//!
//! - `derive` (default):  Enables the derive macro for the `Merge` trait using the `merge_derive`
//!   crate.
//! - `num`: Enables the merge strategies in the `num` module that require the
//!   `num_traits` crate.
//! - `std` (default): Enables the merge strategies in the `hashmap` and `vec` modules that require
//!    the standard library.  If this feature is not set, `merge2` is a `no_std`.
//!
//! # Example
//!
//! ```
//! use merge2::Merge;
//!
//! #[derive(Merge)]
//! struct User {
//!     // Fields with the skip attribute are skipped by Merge
//!     #[merge(skip)]
//!     pub name: &'static str,
//!     pub location: Option<&'static str>,
//!
//!     // The strategy attribute is used to customize the merge behavior
//!     #[merge(strategy = ::merge2::vec::append)]
//!     pub groups: Vec<&'static str>,
//! }
//!
//! let mut defaults = User {
//!     name: "",
//!     location: Some("Internet"),
//!     groups: vec!["rust"],
//! };
//! let mut ferris = User {
//!     name: "Ferris",
//!     location: None,
//!     groups: vec!["mascot"],
//! };
//! ferris.merge(&mut defaults);
//!
//! assert_eq!("Ferris", ferris.name);
//! assert_eq!(Some("Internet"), ferris.location);
//! assert_eq!(vec!["mascot", "rust"], ferris.groups);
//! ```
//!
//! [`Merge`]: trait.Merge.html
//! [`args.rs`]: https://github.com/RoDmitry/merge2/blob/main/examples/args.rs

#![cfg_attr(docsrs, feature(doc_cfg))]
#![cfg_attr(not(feature = "std"), no_std)]

#[cfg_attr(docsrs, doc(cfg(feature = "derive")))]
#[cfg(feature = "derive")]
pub use merge2_derive::*;

/// A trait for objects that can be merged.
///
/// # Deriving
///
/// `Merge` can be derived for structs if the `derive` feature is enabled.  The generated
/// implementation calls the `merge` method for all fields, or the merge strategy function if set.
/// You can use these field attributes to configure the generated implementation:
/// - `skip`: Skip this field in the `merge` method.
/// - `strategy = f`: Call `f(self.field, other.field)` instead of calling the `merge` function for
///    this field.
///
/// You can also set a default strategy for all fields by setting the `strategy` attribute for the
/// struct.
///
/// # Examples
///
/// Deriving `Merge` for a struct:
///
/// ```
/// use merge2::Merge;
///
/// #[derive(Debug, PartialEq, Merge)]
/// struct S {
///     option: Option<usize>,
///
///     #[merge(skip)]
///     s: String,
///
///     #[merge(strategy = ::merge2::bool::overwrite_false)]
///     flag: bool,
/// }
///
/// let mut val = S {
///     option: None,
///     s: "some ignored value".to_owned(),
///     flag: false,
/// };
/// val.merge(&mut S {
///     option: Some(42),
///     s: "some other ignored value".to_owned(),
///     flag: true,
/// });
/// assert_eq!(S {
///     option: Some(42),
///     s: "some ignored value".to_owned(),
///     flag: true,
/// }, val);
/// ```
///
/// Setting a default merge strategy:
///
/// ```
/// use merge2::Merge;
///
/// #[derive(Debug, PartialEq, Merge)]
/// struct S {
///     option1: Option<usize>,
///     option2: Option<usize>,
///     option3: Option<usize>,
/// }
///
/// let mut val = S {
///     option1: None,
///     option2: Some(1),
///     option3: None,
/// };
/// val.merge(&mut S {
///     option1: Some(2),
///     option2: Some(2),
///     option3: None,
/// });
/// assert_eq!(S {
///     option1: Some(2),
///     option2: Some(1),
///     option3: None,
/// }, val);
/// ```
pub trait Merge: Sized {
    /// Merge another object into this object
    fn merge(&mut self, other: &mut Self);
}

/// Merge strategies applicable to any types
pub mod any {
    /// Overwrite `left` with `right` regardless of their values. Sets `right` to a Default value.
    /// Swap would be faster, if you don't need default.
    #[inline]
    pub fn overwrite<T: Default>(left: &mut T, right: &mut T) {
        *left = ::core::mem::take(right);
    }

    /// Overwrite `left` with `right` if the value of `left` is equal to the Default for the type
    #[inline]
    pub fn overwrite_default<T: Default + PartialEq>(left: &mut T, right: &mut T) {
        if *left == T::default() {
            ::core::mem::swap(left, right);
        }
    }

    /// Swap `left` and `right` regardless of their values
    #[inline]
    pub fn swap<T>(left: &mut T, right: &mut T) {
        ::core::mem::swap(left, right);
    }
}

impl<T> Merge for Option<T> {
    /// Overwrite `Option` only if it is `None`
    #[inline]
    fn merge(&mut self, right: &mut Self) {
        if self.is_none() {
            ::core::mem::swap(self, right);
        }
    }
}

/// Merge strategies for `Option`
pub mod option {
    /// On conflict, recursively merge the elements
    #[inline]
    pub fn recursive<T: super::Merge>(left: &mut Option<T>, right: &mut Option<T>) {
        if let Some(original) = left {
            if let Some(new) = right {
                original.merge(new);
            }
        } else {
            ::core::mem::swap(left, right);
        }
    }
}

macro_rules! skip_merge {
    ($($t:ty)*) => {$(
        impl Merge for $t {
            #[inline(always)]
            fn merge(&mut self, _: &mut Self) {}
        }
    )*};
}

skip_merge!(u8 i8 u16 i16 u32 i32 usize isize u64 i64 u128 i128 f32 f64 bool);

/// Merge strategies for `bool`
pub mod bool {
    /// Overwrite left with right if the value of left is false
    #[inline]
    pub fn overwrite_false(left: &mut bool, right: &mut bool) {
        if !*left {
            *left = *right;
        }
    }

    /// Overwrite left with right if the value of left is true
    #[inline]
    pub fn overwrite_true(left: &mut bool, right: &mut bool) {
        if *left {
            *left = *right;
        }
    }
}

/// Merge strategies for numeric types
#[cfg_attr(docsrs, doc(cfg(feature = "num")))]
#[cfg(feature = "num")]
pub mod num {
    /// Set left to the saturated some of left and right
    #[inline]
    pub fn saturating_add<T: num_traits::SaturatingAdd>(left: &mut T, right: &mut T) {
        *left = left.saturating_add(right);
    }
}

/// Merge strategies for types that can be compared (`PartialOrd`)
pub mod ord {
    use ::core::cmp;

    /// Swap elements if `left` is Less than `right`
    #[inline]
    pub fn max<T: cmp::PartialOrd>(left: &mut T, right: &mut T) {
        if cmp::PartialOrd::partial_cmp(left, right) == Some(cmp::Ordering::Less) {
            ::core::mem::swap(left, right);
        }
    }

    /// Swap elements if `left` is Greater than `right`
    #[inline]
    pub fn min<T: cmp::PartialOrd>(left: &mut T, right: &mut T) {
        if cmp::PartialOrd::partial_cmp(left, right) == Some(cmp::Ordering::Greater) {
            ::core::mem::swap(left, right);
        }
    }
}

#[cfg_attr(docsrs, doc(cfg(feature = "std")))]
#[cfg(feature = "std")]
mod std {
    use super::Merge;

    impl Merge for &str {
        #[inline]
        fn merge(&mut self, right: &mut Self) {
            if self.is_empty() {
                ::core::mem::swap(self, right);
            }
        }
    }

    impl Merge for String {
        #[inline]
        fn merge(&mut self, right: &mut Self) {
            if self.is_empty() {
                ::core::mem::swap(self, right);
            }
        }
    }

    /// Merge strategies for `String`
    pub mod string {
        /// Append the contents of right to left
        #[inline]
        pub fn append(left: &mut String, right: &mut String) {
            if left.is_empty() {
                ::core::mem::swap(left, right);
            } else {
                let new = ::core::mem::take(right);
                left.push_str(&new);
            }
        }

        /// Prepend the contents of right to left
        #[inline]
        pub fn prepend(left: &mut String, right: &mut String) {
            if left.is_empty() {
                ::core::mem::swap(left, right);
            } else if !right.is_empty() {
                right.push_str(left);
                *left = ::core::mem::take(right);
            }
        }
    }

    impl<T> Merge for Vec<T> {
        #[inline]
        fn merge(&mut self, right: &mut Self) {
            if self.is_empty() {
                ::core::mem::swap(self, right);
            }
        }
    }

    /// Merge strategies for `Vec`
    pub mod vec {
        /// Append the contents of right to left
        #[inline]
        pub fn append<T>(left: &mut Vec<T>, right: &mut Vec<T>) {
            if left.is_empty() {
                ::core::mem::swap(left, right);
            } else {
                left.append(right);
            }
        }

        /// Prepend the contents of right to left
        #[inline]
        pub fn prepend<T>(left: &mut Vec<T>, right: &mut Vec<T>) {
            if left.is_empty() {
                ::core::mem::swap(left, right);
            } else if !right.is_empty() {
                right.append(left);
                ::core::mem::swap(left, right);
            }
        }
    }

    use ::std::collections::HashMap;
    impl<K, V> Merge for HashMap<K, V> {
        #[inline]
        fn merge(&mut self, right: &mut Self) {
            if self.is_empty() {
                ::core::mem::swap(self, right);
            }
        }
    }

    /// Merge strategies for `HashMap`
    pub mod hashmap {
        use super::HashMap;
        use ::core::hash::BuildHasher;
        use ::core::hash::Hash;

        /// On conflict, merge elements from `right` to `left`.
        ///
        /// In other words, this gives precedence to `left`.
        #[inline]
        pub fn merge<K: Eq + Hash, V, S: BuildHasher + Default>(
            left: &mut HashMap<K, V, S>,
            right: &mut HashMap<K, V, S>,
        ) {
            let map = ::core::mem::take(right);
            for (k, v) in map {
                left.entry(k).or_insert(v);
            }
        }

        /// On conflict, replace elements of `left` with `right`.
        ///
        /// In other words, this gives precedence to `right`.
        #[inline]
        pub fn replace<K: Eq + Hash, V, S: BuildHasher + Default>(
            left: &mut HashMap<K, V, S>,
            right: &mut HashMap<K, V, S>,
        ) {
            left.extend(::core::mem::take(right))
        }

        /// On conflict, recursively merge the elements
        pub fn recursive<K: Eq + Hash, V: super::Merge, S: BuildHasher + Default>(
            left: &mut HashMap<K, V, S>,
            right: &mut HashMap<K, V, S>,
        ) {
            use ::std::collections::hash_map::Entry;

            let map = ::core::mem::take(right);
            for (k, mut v) in map {
                match left.entry(k) {
                    Entry::Occupied(mut existing) => existing.get_mut().merge(&mut v),
                    Entry::Vacant(empty) => {
                        empty.insert(v);
                    }
                }
            }
        }

        /// Merge recursively elements only if the key is present in `left` and `right`
        pub fn intersection<K: Eq + Hash, V: super::Merge, S: BuildHasher + Default>(
            left: &mut HashMap<K, V, S>,
            right: &mut HashMap<K, V, S>,
        ) {
            use ::std::collections::hash_map::Entry;

            let map = ::core::mem::take(right);
            for (k, mut v) in map {
                if let Entry::Occupied(mut existing) = left.entry(k) {
                    existing.get_mut().merge(&mut v);
                }
            }
        }
    }
}

pub use std::*;