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
use std::{collections::HashMap, path::PathBuf};

use indexmap::IndexMap;
pub use swc_config_macro::Merge;

/// Deriavable trait for overrding configurations.
///
/// Typically, correct implementation of this trait for a struct is calling
/// merge for all fields, and `#[derive(Merge)]` will do it for you.
pub trait Merge: Sized {
    /// `self` has higher priority.
    fn merge(&mut self, other: Self);
}

/// Modifies `self` iff `self` is [None]
impl<T> Merge for Option<T> {
    #[inline]
    fn merge(&mut self, other: Self) {
        if self.is_none() {
            *self = other;
        }
    }
}

impl<T> Merge for Box<T>
where
    T: Merge,
{
    #[inline]
    fn merge(&mut self, other: Self) {
        (**self).merge(*other);
    }
}

/// Modifies `self` iff `self` is empty.
impl<T> Merge for Vec<T> {
    #[inline]
    fn merge(&mut self, other: Self) {
        if self.is_empty() {
            *self = other;
        }
    }
}

/// Modifies `self` iff `self` is empty.
impl<K, V, S> Merge for HashMap<K, V, S> {
    #[inline]
    fn merge(&mut self, other: Self) {
        if self.is_empty() {
            *self = other;
        }
    }
}

/// Modifies `self` iff `self` is empty.
impl<K, V, S> Merge for IndexMap<K, V, S> {
    #[inline]
    fn merge(&mut self, other: Self) {
        if self.is_empty() {
            *self = other;
        }
    }
}

/// Modifies `self` iff `self` is empty.
impl Merge for String {
    #[inline]
    fn merge(&mut self, other: Self) {
        if self.is_empty() {
            *self = other;
        }
    }
}

/// Modifies `self` iff `self` is empty.
impl Merge for PathBuf {
    #[inline]
    fn merge(&mut self, other: Self) {
        if self.as_os_str().is_empty() {
            *self = other;
        }
    }
}