use std::future::Future;
use std::pin::Pin;
use std::task::Context;
use std::task::Poll;
use tokio::sync::oneshot;
use tokio::sync::oneshot::Receiver;
#[must_use]
#[derive(Debug)]
pub struct RayonHandle<T> {
rx: Receiver<T>,
}
impl<T> RayonHandle<T>
where
T: Send + 'static,
{
pub fn spawn<F: FnOnce() -> T + Send + 'static>(func: F) -> Self {
let (tx, rx) = oneshot::channel();
rayon::spawn(move || {
if !tx.is_closed() {
tx.send(func()).ok();
}
});
Self { rx }
}
}
impl<T> Future for RayonHandle<T> {
type Output = T;
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
let rx = Pin::new(&mut self.rx);
rx.poll(cx)
.map(|result| result.expect("failed to receive from oneshot channel"))
}
}