use futures01::{Async, Future};
use std::error::Error;
use std::sync::mpsc::{channel, Receiver, Sender};
use std::thread;
pub struct Futurified<T: Send + 'static, F: FnOnce() -> T + Send, E: Error> {
tx: Sender<T>,
rx: Receiver<T>,
wrapped: Option<F>,
is_running: bool,
error: std::marker::PhantomData<E>,
}
pub fn wrap<T: Send + 'static, F: FnOnce() -> T + Send + 'static, E: Error>(
wrapped: F,
) -> Futurified<T, F, E> {
let (tx, rx) = channel();
Futurified {
tx,
rx,
wrapped: Some(wrapped),
is_running: false,
error: std::marker::PhantomData,
}
}
pub fn wrap_eager<T: Send + 'static, F: FnOnce() -> T + Send + 'static, E: Error>(
wrapped: F,
) -> Futurified<T, F, E> {
let mut this = wrap(wrapped);
this.run();
this
}
impl<T: Send + 'static, F: FnOnce() -> T + Send + 'static, E: Error> Futurified<T, F, E> {
fn run(&mut self) {
self.is_running = true;
let tx = self.tx.clone();
let sfn = self.wrapped.take().unwrap();
thread::spawn(move || {
let result = sfn();
if let Err(e) = tx.send(result) {
println!("Error sending result: {}", e)
}
});
}
}
impl<T: Send + 'static, F: FnOnce() -> T + Send + 'static, E: Error> Future
for Futurified<T, F, E>
{
type Item = T;
type Error = E;
fn poll(&mut self) -> Result<Async<Self::Item>, Self::Error> {
if !self.is_running {
self.run();
}
if let Ok(x) = self.rx.try_recv() {
Ok(Async::Ready(x))
} else {
Ok(Async::NotReady)
}
}
}