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
use eval::{Fields, ParamEval, TildeExpansion, WordEval, WordEvalConfig};
use future::{Async, EnvFuture, Poll};
use super::is_present;

/// A future representing a `Alternative` parameter substitution evaluation.
#[must_use = "futures do nothing unless polled"]
#[derive(Debug)]
pub struct Alternative<F> {
    state: State<F>,
}

#[derive(Debug)]
enum State<F> {
    Zero,
    Alternative(F),
}

/// Constructs future representing a `Alternative` parameter substitution evaluation.
///
/// First, `param` will be evaluated and if the result is non-empty, or if the
/// result is defined-but-empty and `strict = false`, then `alternative` will be
/// evaluated and yielded.
///
/// Otherwise, `Fields::Zero` will be returned (i.e. the value of `param`).
///
/// Note: field splitting will neither be done on the parameter, nor the alternative word.
pub fn alternative<P: ?Sized, W, E: ?Sized>(
    strict: bool,
    param: &P,
    alternative: Option<W>,
    env: &E,
    cfg: TildeExpansion
) -> Alternative<W::EvalFuture>
    where P: ParamEval<E, EvalResult = W::EvalResult>,
          W: WordEval<E>,
{
    let state = match (is_present(strict, param.eval(false, env)).is_some(), alternative) {
        (true, Some(w)) => {
            let future = w.eval_with_config(env, WordEvalConfig {
                split_fields_further: false,
                tilde_expansion: cfg,
            });
            State::Alternative(future)
        },

        (true, None) |
        (false, _) => State::Zero,
    };

    Alternative {
        state: state,
    }
}

impl<T, F, E: ?Sized> EnvFuture<E> for Alternative<F>
    where F: EnvFuture<E, Item = Fields<T>>,
{
    type Item = F::Item;
    type Error = F::Error;

    fn poll(&mut self, env: &mut E) -> Poll<Self::Item, Self::Error> {
        match self.state {
            State::Zero => Ok(Async::Ready(Fields::Zero)),
            State::Alternative(ref mut f) => f.poll(env),
        }
    }

    fn cancel(&mut self, env: &mut E) {
        match self.state {
            State::Zero => {},
            State::Alternative(ref mut f) => f.cancel(env),
        }
    }
}