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
use {CANCELLED_TWICE, POLLED_TWICE, Spawn};
use env::{SetArgumentsEnvironment, FunctionEnvironment};
use future::{Async, EnvFuture, Poll};
use std::fmt;

/// Creates a future adapter that will attempt to execute a function (if it has
/// been defined) with a given set of arguments.
pub fn function<A, E: ?Sized>(name: &E::FnName, args: A, env: &E) -> Option<Function<E::Fn, E>>
    where E: FunctionEnvironment + SetArgumentsEnvironment,
          E::Args: From<A>,
          E::Fn: Clone + Spawn<E>,
{
    env.function(name).cloned().map(|func| function_body(func, args))
}

/// Creates a future adapter that will execute a function body with the given set of arguments.
pub fn function_body<S, A, E: ?Sized>(body: S, args: A) -> Function<S, E>
    where S: Spawn<E>,
          E: SetArgumentsEnvironment,
          E::Args: From<A>,
{
    Function {
        state: State::Init(Some((body, args.into()))),
    }
}

/// A future that represents the execution of a function registered in an environment.
#[must_use = "futures do nothing unless polled"]
pub struct Function<S, E: ?Sized>
    where S: Spawn<E>,
          E: SetArgumentsEnvironment,
{
    state: State<S, S::EnvFuture, E::Args>,
}

#[derive(Debug)]
enum State<S, F, A> {
    Init(Option<(S, A)>),
    Pending(F, Option<A>),
    Gone,
}

impl<S, E: ?Sized> fmt::Debug for Function<S, E>
    where S: Spawn<E> + fmt::Debug,
          S::EnvFuture: fmt::Debug,
          E: SetArgumentsEnvironment,
          E::Args: fmt::Debug,
{
    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
        fmt.debug_struct("Function")
            .field("state", &self.state)
            .finish()
    }
}

impl<S, E: ?Sized> EnvFuture<E> for Function<S, E>
    where S: Spawn<E>,
          E: SetArgumentsEnvironment,
{
    type Item = 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::Init(ref mut func_args) => {
                    let (func, args) = func_args.take().expect(POLLED_TWICE);
                    let old_args = env.set_args(args);

                    State::Pending(func.spawn(env), Some(old_args))
                },

                State::Pending(ref mut f, ref mut old_args) => match f.poll(env) {
                    Ok(Async::NotReady) => return Ok(Async::NotReady),
                    ret => {
                        env.set_args(old_args.take().expect(POLLED_TWICE));
                        return ret;
                    },
                },

                State::Gone => panic!(POLLED_TWICE),
            };

            self.state = next_state;
        }
    }

    fn cancel(&mut self, env: &mut E) {
        match self.state {
            State::Init(_) => {},
            State::Pending(ref mut f, ref mut old_args) => {
                let old_args = old_args.take().expect(CANCELLED_TWICE);
                f.cancel(env);
                env.set_args(old_args);
            },
            State::Gone => panic!(CANCELLED_TWICE),
        }

        self.state = State::Gone;
    }
}