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
use {EXIT_SUCCESS, Spawn};
use error::IsFatalError;
use env::{LastStatusEnvironment, ReportErrorEnvironment};
use future::{Async, EnvFuture, Poll};
use spawn::{EnvFutureExt, ExitResult, FlattenedEnvFuture, GuardBodyPair, Sequence, sequence,
            SwallowNonFatal, swallow_non_fatal_errors};
use std::fmt;

/// Spawns an `If` commands from number of conditional branches.
///
/// If any guard evaluates with a successful exit status, then only its
/// corresponding body will be evaluated. If no guard exits successfully,
/// the `else` branch will be run, if present. Otherwise, the `If` command
/// will exit successfully.
pub fn if_cmd<C, I, E: ?Sized>(conditionals: C, else_branch: Option<I>) -> If<C::IntoIter, I, E>
    where C: IntoIterator<Item = GuardBodyPair<I>>,
          I: IntoIterator,
          I::Item: Spawn<E>,
{
    If {
        state: State::Conditionals {
            current: None,
            conditionals: conditionals.into_iter(),
            else_branch: else_branch,
        }
    }
}

/// A future representing the execution of an `if` command.
#[must_use = "futures do nothing unless polled"]
pub struct If<C, I, E: ?Sized>
    where I: IntoIterator,
          I::Item: Spawn<E>,
{
    state: State<C, I, E>,
}

impl<S, C, I, E: ?Sized> fmt::Debug for If<C, I, E>
    where C: fmt::Debug,
          I: IntoIterator<Item = S> + fmt::Debug,
          I::IntoIter: fmt::Debug,
          S: Spawn<E> + fmt::Debug,
          S::EnvFuture: fmt::Debug,
          S::Future: fmt::Debug,
{
    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
        fmt.debug_struct("If")
            .field("state", &self.state)
            .finish()
    }
}

enum State<C, I, E: ?Sized>
    where I: IntoIterator,
          I::Item: Spawn<E>,
{
    Conditionals {
        current: Option<Branch<I::IntoIter, E>>,
        conditionals: C,
        else_branch: Option<I>,
    },

    Body(Sequence<I::IntoIter, E>),
}

impl<S, C, I, E: ?Sized> fmt::Debug for State<C, I, E>
    where C: fmt::Debug,
          I: IntoIterator<Item = S> + fmt::Debug,
          I::IntoIter: fmt::Debug,
          S: Spawn<E> + fmt::Debug,
          S::EnvFuture: fmt::Debug,
          S::Future: fmt::Debug,
{
    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
        match *self {
            State::Conditionals { ref current, ref conditionals, ref else_branch } => {
                fmt.debug_struct("State::Conditionals")
                    .field("current", current)
                    .field("conditionals", conditionals)
                    .field("else_branch", else_branch)
                    .finish()
            },
            State::Body(ref b) => fmt.debug_tuple("State::Body")
                .field(b)
                .finish(),
        }
    }
}

impl<S, C, I, E: ?Sized> EnvFuture<E> for If<C, I, E>
    where E: LastStatusEnvironment + ReportErrorEnvironment,
          C: Iterator<Item = GuardBodyPair<I>>,
          I: IntoIterator<Item = S>,
          S: Spawn<E>,
          S::Error: IsFatalError,
{
    type Item = ExitResult<S::Future>;
    type Error = S::Error;

    fn poll(&mut self, env: &mut E) -> Poll<Self::Item, Self::Error> {
        loop {
            let next_state = match self.state {
                State::Conditionals {
                    ref mut current,
                    ref mut conditionals,
                    ref mut else_branch
                } => {
                    let body = if let Some(ref mut branch) = *current {
                        try_ready!(branch.poll(env))
                    } else {
                        None
                    };

                    match body {
                        Some(body) => State::Body(sequence(body)),
                        None => match conditionals.next() {
                            Some(GuardBodyPair { guard, body }) => {
                                let guard = sequence(guard).flatten_future();

                                *current = Some(Branch {
                                    guard: swallow_non_fatal_errors(guard),
                                    body: Some(body.into_iter()),
                                });

                                continue;
                            },

                            None => {
                                match else_branch.take() {
                                    Some(els) => State::Body(sequence(els)),
                                    None => {
                                        let exit = ExitResult::Ready(EXIT_SUCCESS);
                                        return Ok(Async::Ready(exit));
                                    },
                                }
                            }
                        },
                    }
                }

                State::Body(ref mut f) => return f.poll(env),
            };

            self.state = next_state;
        }
    }

    fn cancel(&mut self, env: &mut E) {
        match self.state {
            State::Conditionals { ref mut current, ..  } => {
                if let Some(ref mut branch) = *current {
                    branch.cancel(env)
                }
            },

            State::Body(ref mut f) => f.cancel(env),
        }
    }
}

type FlattenedSequence<I, F, E> = FlattenedEnvFuture<Sequence<I, E>, ExitResult<F>>;

/// A future which represents the resolution of a conditional guard in an `If` command.
///
/// If the guard exits successfully, its corresponding body is yielded back, so that it
/// can be run by the caller.
#[must_use = "futures do nothing unless polled"]
struct Branch<I, E: ?Sized>
    where I: Iterator,
          I::Item: Spawn<E>,
{
    guard: SwallowNonFatal<FlattenedSequence<I, <I::Item as Spawn<E>>::Future, E>>,
    body: Option<I>,
}

impl<I, S, E: ?Sized> fmt::Debug for Branch<I, E>
    where I: Iterator<Item = S> + fmt::Debug,
          S: Spawn<E> + fmt::Debug,
          S::EnvFuture: fmt::Debug,
          S::Future: fmt::Debug,
{
    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
        fmt.debug_struct("Branch")
            .field("guard", &self.guard)
            .field("body", &self.body)
            .finish()
    }
}

impl<S, I, E: ?Sized> EnvFuture<E> for Branch<I, E>
    where E: LastStatusEnvironment + ReportErrorEnvironment,
          I: Iterator<Item = S>,
          S: Spawn<E>,
          S::Error: IsFatalError,
{
    type Item = Option<I>;
    type Error = S::Error;

    fn poll(&mut self, env: &mut E) -> Poll<Self::Item, Self::Error> {
        let status = try_ready!(self.guard.poll(env));
        env.set_last_status(status);

        let ret = if status.success() {
            Some(self.body.take().expect("polled twice"))
        } else {
            None
        };

        Ok(Async::Ready(ret))
    }

    fn cancel(&mut self, env: &mut E) {
        self.guard.cancel(env)
    }
}