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
use Fd;
use io::{FileDesc, Permissions};
use env::{AsyncIoEnvironment, FileDescEnvironment};
use eval::RedirectAction;
use std::collections::HashMap;
use std::fmt;
use std::io::Result as IoResult;

/// An interface for maintaining a state of all file descriptors 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 RedirectEnvRestorer<E: ?Sized> {
    /// Reserves capacity for at least `additional` more redirects to be backed up.
    fn reserve(&mut self, additional: usize);

    /// Applies changes to a given environment after backing up as appropriate.
    fn apply_action(&mut self, action: RedirectAction<E::FileHandle>, env: &mut E) -> IoResult<()>
        where E: AsyncIoEnvironment + FileDescEnvironment,
              E::FileHandle: From<FileDesc>;

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

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

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

    fn apply_action(&mut self, action: RedirectAction<E::FileHandle>, env: &mut E) -> IoResult<()>
        where E: AsyncIoEnvironment + FileDescEnvironment,
              E::FileHandle: From<FileDesc>
    {
        (**self).apply_action(action, env)
    }

    fn backup(&mut self, fd: Fd, env: &mut E) {
        (**self).backup(fd, env)
    }

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

/// Maintains a state of all file descriptors 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 RedirectRestorer<E: ?Sized>
    where E: FileDescEnvironment,
{
    /// Any overrides that have been applied (and be undone).
    overrides: HashMap<Fd, Option<(E::FileHandle, Permissions)>>,
}

impl<E: ?Sized> Eq for RedirectRestorer<E>
    where E: FileDescEnvironment,
          E::FileHandle: Eq,
{}

impl<E: ?Sized> PartialEq<Self> for RedirectRestorer<E>
    where E: FileDescEnvironment,
          E::FileHandle: PartialEq,
{
    fn eq(&self, other: &Self) -> bool {
        self.overrides == other.overrides
    }
}

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

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

impl<E: ?Sized> RedirectRestorer<E>
    where E: FileDescEnvironment,
{
    /// Create a new wrapper.
    pub fn new() -> Self {
        RedirectRestorer {
            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 {
        RedirectRestorer {
            overrides: HashMap::with_capacity(capacity),
        }
    }

    /// Reserves capacity for at least `additional` more redirects to be backed up.
    #[deprecated(note = "use the `RedirectEnvRestorer` trait instead")]
    pub fn reserve(&mut self, additional: usize) {
        self.overrides.reserve(additional);
    }

    /// Applies changes to a given environment after backing up as appropriate.
    #[deprecated(note = "use the `RedirectEnvRestorer` trait instead")]
    pub fn apply_action(&mut self, action: RedirectAction<E::FileHandle>, env: &mut E)
        -> IoResult<()>
        where E: AsyncIoEnvironment,
              E::FileHandle: Clone + From<FileDesc>,
    {
        RedirectEnvRestorer::apply_action(self, action, env)
    }

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

    /// Restore all file descriptors to their original state.
    #[deprecated(note = "use the `RedirectEnvRestorer` trait instead")]
    pub fn restore(mut self, env: &mut E) {
        self._restore(env)
    }

    fn _restore(&mut self, env: &mut E) {
        for (fd, backup) in self.overrides.drain() {
            match backup {
                Some((handle, perms)) => env.set_file_desc(fd, handle, perms),
                None => env.close_file_desc(fd),
            }
        }
    }
}

impl<E: ?Sized> RedirectEnvRestorer<E> for RedirectRestorer<E>
    where E: FileDescEnvironment,
          E::FileHandle: Clone
{
    fn reserve(&mut self, additional: usize) {
        self.overrides.reserve(additional);
    }

    fn apply_action(&mut self, action: RedirectAction<E::FileHandle>, env: &mut E) -> IoResult<()>
        where E: AsyncIoEnvironment + FileDescEnvironment,
              E::FileHandle: From<FileDesc>
    {
        match action {
            RedirectAction::Close(fd) |
            RedirectAction::Open(fd, _, _) |
            RedirectAction::HereDoc(fd, _) => self.backup(fd, env),
        }

        action.apply(env)
    }

    fn backup(&mut self, fd: Fd, env: &mut E) {
        self.overrides.entry(fd).or_insert_with(|| {
            env.file_desc(fd).map(|(handle, perms)| (handle.clone(), perms))
        });
    }

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