use std::pin::Pin;
use futures::future::FutureObj;
use futures::prelude::*;
use futures::task::{Context, Poll, Spawn, SpawnError};
#[derive(Debug)]
pub struct Spawner {
_reserved: (),
}
impl Spawner {
pub fn new() -> Self {
Self { _reserved: () }
}
}
impl Default for Spawner {
fn default() -> Self {
Self::new()
}
}
impl Clone for Spawner {
fn clone(&self) -> Self {
Self::new()
}
}
impl Spawn for Spawner {
fn spawn_obj(&mut self, future: FutureObj<'static, ()>) -> Result<(), SpawnError> {
(&*self).spawn_obj(future)
}
}
impl<'a> Spawn for &'a Spawner {
fn spawn_obj(&mut self, future: FutureObj<'static, ()>) -> Result<(), SpawnError> {
runtime_raw::current_runtime().spawn_boxed(future.boxed())
}
}
pub fn spawn<F, T>(fut: F) -> JoinHandle<T>
where
F: Future<Output = T> + Send + 'static,
T: Send + 'static,
{
let (tx, rx) = futures::channel::oneshot::channel();
let fut = async move {
let t = fut.await;
let _ = tx.send(t);
};
runtime_raw::current_runtime()
.spawn_boxed(fut.boxed())
.expect("cannot spawn a future");
JoinHandle { rx }
}
#[derive(Debug)]
pub struct JoinHandle<T> {
pub(crate) rx: futures::channel::oneshot::Receiver<T>,
}
impl<T> Future for JoinHandle<T> {
type Output = T;
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
match self.rx.poll_unpin(cx) {
Poll::Pending => Poll::Pending,
Poll::Ready(Ok(t)) => Poll::Ready(t),
Poll::Ready(Err(_)) => panic!(), }
}
}