use super::job::*;
use std::mem;
use futures::future::{Future, FutureObj, FutureExt};
use futures::task::{Context, Poll};
enum JobState<TFn> {
FutureNotCreated(TFn),
WaitingForFuture(FutureObj<'static, ()>),
Completed
}
impl<TFn, TFuture> JobState<TFn>
where TFn: FnOnce() -> TFuture+Send,
TFuture: 'static+Send+Future<Output=()> {
fn take(&mut self) -> Option<FutureObj<'static, ()>> {
let mut value = JobState::Completed;
mem::swap(self, &mut value);
match value {
JobState::FutureNotCreated(create_fn) => Some(FutureObj::new(Box::new(create_fn()))),
JobState::WaitingForFuture(future) => Some(future),
JobState::Completed => None
}
}
}
pub struct FutureJob<TFn> {
action: JobState<TFn>
}
impl<TFn, TFuture> FutureJob<TFn>
where TFn: FnOnce() -> TFuture+Send,
TFuture: 'static+Send+Future<Output=()> {
pub fn new(create_future: TFn) -> FutureJob<TFn> {
FutureJob { action: JobState::FutureNotCreated(create_future) }
}
}
impl<TFn, TFuture> ScheduledJob for FutureJob<TFn>
where TFn: FnOnce() -> TFuture+Send,
TFuture: 'static+Send+Future<Output=()> {
fn run(&mut self, context: &mut Context) -> Poll<()> {
let action = self.action.take();
if let Some(mut action) = action {
match action.poll_unpin(context) {
Poll::Ready(()) => Poll::Ready(()),
Poll::Pending => {
self.action = JobState::WaitingForFuture(action);
Poll::Pending
}
}
} else {
panic!("Cannot schedule an action twice");
}
}
}