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
use env::{ExportedVariableEnvironment, VariableEnvironment, UnsetVariableEnvironment};
use std::collections::HashMap;
use std::fmt;

/// An interface for maintaining a state of all variable definitions that have
/// been modified so that they can be restored later.
///
/// > *Note*: the caller should take care that a restorer instance is always
/// > called with the same environment for its entire lifetime. Using different
/// > environments with the same restorer instance will undoubtedly do the wrong
/// > thing eventually, and no guarantees can be made.
pub trait VarEnvRestorer<E: ?Sized + VariableEnvironment> {
    /// Reserves capacity for at least `additional` more variables to be backed up.
    fn reserve(&mut self, additional: usize);

    /// Backup and set the value of some variable (and its exported status).
    #[deprecated(note = "Use `VarEnvRestorer2::set_exported_var2` instead")]
    fn set_exported_var(&mut self, name: E::VarName, val: E::Var, exported: bool, env: &mut E);

    /// Backup and unset the value of some variable (including environment variables).
    fn unset_var(&mut self, name: E::VarName, env: &mut E);

    /// Backs up the original value of specified variable.
    ///
    /// The original value of the variable is the one the environment
    /// held before it was passed into this wrapper. That is, if a variable
    /// is backed up multiple times, only the value before the first
    /// call could be restored later.
    fn backup(&mut self, key: E::VarName, env: &E);

    /// Restore all variable definitions to their original state.
    fn restore(&mut self, env: &mut E);
}

impl<'a, T, E: ?Sized> VarEnvRestorer<E> for &'a mut T
    where T: VarEnvRestorer<E>,
          E: VariableEnvironment,
{
    fn reserve(&mut self, additional: usize) {
        (**self).reserve(additional);
    }

    #[allow(deprecated)]
    fn set_exported_var(&mut self, name: E::VarName, val: E::Var, exported: bool, env: &mut E) {
        (**self).set_exported_var(name, val, exported, env);
    }

    fn unset_var(&mut self, name: E::VarName, env: &mut E) {
        (**self).unset_var(name, env);
    }

    fn backup(&mut self, key: E::VarName, env: &E) {
        (**self).backup(key, env);
    }

    fn restore(&mut self, env: &mut E) {
        (**self).restore(env);
    }
}

/// A corrected extension of the `VarEnvRestorer` trait, provided in a backwards
/// compatible manner to avoid changes on the original trait.
///
/// An interface for maintaining a state of all variable definitions that have
/// been modified so that they can be restored later.
///
/// > *Note*: the caller should take care that a restorer instance is always
/// > called with the same environment for its entire lifetime. Using different
/// > environments with the same restorer instance will undoubtedly do the wrong
/// > thing eventually, and no guarantees can be made.
pub trait VarEnvRestorer2<E: ?Sized + VariableEnvironment>: VarEnvRestorer<E> {
    /// Backup and set the value of some variable, either explicitly setting its
    /// exported status as specified, or maintaining its status as an environment
    /// variable if previously set as such.
    fn set_exported_var2(
        &mut self,
        name: E::VarName,
        val: E::Var,
        exported: Option<bool>,
        env: &mut E
    );
}

impl<'a, T, E: ?Sized> VarEnvRestorer2<E> for &'a mut T
    where T: VarEnvRestorer2<E>,
          E: VariableEnvironment,
{
    fn set_exported_var2(
        &mut self,
        name: E::VarName,
        val: E::Var,
        exported: Option<bool>,
        env: &mut E
    ) {
        (**self).set_exported_var2(name, val, exported, env);
    }
}

/// Maintains a state of all variable definitions that have been modified so that
/// they can be restored later.
///
/// > *Note*: the caller should take care that a restorer instance is always
/// > called with the same environment for its entire lifetime. Using different
/// > environments with the same restorer instance will undoubtedly do the wrong
/// > thing eventually, and no guarantees can be made.
#[derive(Clone)]
pub struct VarRestorer<E: ?Sized>
    where E: VariableEnvironment,
{
    /// Any overrides that have been applied (and be undone).
    overrides: HashMap<E::VarName, Option<(E::Var, bool)>>,
}

impl<E: ?Sized> Eq for VarRestorer<E>
    where E: VariableEnvironment,
          E::VarName: Eq,
          E::Var: Eq,
{}

impl<E: ?Sized> PartialEq<Self> for VarRestorer<E>
    where E: VariableEnvironment,
          E::VarName: Eq,
          E::Var: Eq,
{
    fn eq(&self, other: &Self) -> bool {
        self.overrides == other.overrides
    }
}

impl<E: ?Sized> fmt::Debug for VarRestorer<E>
    where E: VariableEnvironment,
          E::VarName: fmt::Debug,
          E::Var: fmt::Debug,
{
    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
        fmt.debug_struct("VarRestorer")
            .field("overrides", &self.overrides)
            .finish()
    }
}

impl<E: ?Sized> Default for VarRestorer<E>
    where E: VariableEnvironment,
{
    fn default() -> Self {
        Self::new()
    }
}

impl<E: ?Sized> VarRestorer<E>
    where E: VariableEnvironment,
{
    /// Create a new wrapper.
    pub fn new() -> Self {
        VarRestorer {
            overrides: HashMap::new(),
        }
    }

    /// Create a new wrapper and reserve capacity for backing up the previous
    /// file descriptors of the environment.
    pub fn with_capacity(capacity: usize) -> Self {
        VarRestorer {
            overrides: HashMap::with_capacity(capacity),
        }
    }

    /// Restore all variable definitions to their original state.
    #[deprecated(note = "use the `VarEnvRestorer` trait instead")]
    pub fn restore(mut self, env: &mut E)
        where E: ExportedVariableEnvironment + UnsetVariableEnvironment,
    {
        self._restore(env);
    }

    fn _restore(&mut self, env: &mut E)
        where E: ExportedVariableEnvironment + UnsetVariableEnvironment,
    {
        for (key, val) in self.overrides.drain() {
            match val {
                Some((val, exported)) => env.set_exported_var(key, val, exported),
                None => env.unset_var(&key),
            }
        }
    }
}

impl<E: ?Sized> VarRestorer<E>
    where E: ExportedVariableEnvironment,
          E::VarName: Clone,
          E::Var: Clone,
{
    /// Backup and set the value of some variable, maintaining its status as an
    /// environment variable if previously set as such.
    #[deprecated(note = "use the `VarEnvRestorer` trait instead")]
    pub fn set_exported_var(&mut self, name: E::VarName, val: E::Var, exported: bool, env: &mut E) {
        self._set_exported_var(name, val, Some(exported), env);
    }

    fn _set_exported_var(
        &mut self,
        name: E::VarName,
        val: E::Var,
        exported: Option<bool>,
        env: &mut E
    ) {
        self._backup(name.clone(), env);

        match exported {
            Some(exported) => env.set_exported_var(name, val, exported),
            None => env.set_var(name, val),
        }
    }

    /// Backup and unset the value of some variable (including environment
    /// variables).
    #[deprecated(note = "use the `VarEnvRestorer` trait instead")]
    pub fn unset_var(&mut self, name: E::VarName, env: &mut E)
        where E: UnsetVariableEnvironment,
    {
        VarEnvRestorer::unset_var(self, name, env)
    }

    /// Backs up the original value of specified variable.
    ///
    /// The original value of the variable is the one the environment
    /// held before it was passed into this wrapper. That is, if a variable
    /// is backed up multiple times, only the value before the first
    /// call could be restored later.
    #[deprecated(note = "use the `VarEnvRestorer` trait instead")]
    pub fn backup(&mut self, key: E::VarName, env: &E) {
        self._backup(key, env);
    }

    fn _backup(&mut self, key: E::VarName, env: &E) {
        let value = env.exported_var(&key);
        self.overrides.entry(key).or_insert_with(|| {
            value.map(|(val, exported)| (val.clone(), exported))
        });
    }
}

impl<E: ?Sized> VarEnvRestorer<E> for VarRestorer<E>
    where E: ExportedVariableEnvironment + UnsetVariableEnvironment,
          E::VarName: Clone,
          E::Var: Clone,
{
    fn reserve(&mut self, additional: usize) {
        self.overrides.reserve(additional);
    }

    fn set_exported_var(&mut self, name: E::VarName, val: E::Var, exported: bool, env: &mut E) {
        self._set_exported_var(name, val, Some(exported), env);
    }

    fn unset_var(&mut self, name: E::VarName, env: &mut E) {
        self._backup(name.clone(), env);
        env.unset_var(&name);
    }

    fn backup(&mut self, key: E::VarName, env: &E) {
        self._backup(key, env);
    }

    fn restore(&mut self, env: &mut E) {
        self._restore(env);
    }
}

impl<E: ?Sized> VarEnvRestorer2<E> for VarRestorer<E>
    where E: ExportedVariableEnvironment + UnsetVariableEnvironment,
          E::VarName: Clone,
          E::Var: Clone,
{
    fn set_exported_var2(
        &mut self,
        name: E::VarName,
        val: E::Var,
        exported: Option<bool>,
        env: &mut E
    ) {
        self._set_exported_var(name, val, exported, env);
    }
}