use std::cell::RefCell;
use std::future::Future;
use std::pin::Pin;
use std::task::{Context, Poll};
#[cfg(not(any(feature = "tokio-oneshot", feature = "futures-channel")))]
compile_error!("One of tokio-oneshot or futures-channel (default) \
features is required for this crate!");
#[cfg(feature="tokio-oneshot")]
use tokio::sync::oneshot;
#[cfg(not(feature="tokio-oneshot"))]
use futures_channel::oneshot;
use crate::{Canceled, DispatchPool};
thread_local!(static POOL: RefCell<Option<DispatchPool>> = RefCell::new(None));
pub fn register_dispatch_pool(pool: DispatchPool) -> Option<DispatchPool> {
POOL.with(|p| p.replace(Some(pool)))
}
pub fn deregister_dispatch_pool() -> Option<DispatchPool> {
POOL.with(|p| p.replace(None))
}
pub fn is_dispatch_pool_registered() -> bool {
POOL.with(|p| p.borrow().is_some())
}
pub fn dispatch<F>(f: F) -> Option<F>
where F: FnOnce() + Send + 'static
{
POOL.with(|p| {
if let Some(pool) = p.borrow().as_ref() {
pool.spawn(Box::new(f));
None
} else {
Some(f)
}
})
}
#[must_use = "futures do nothing unless awaited or polled"]
pub enum DispatchRx<F, T> {
Dispatch(Dispatched<T>),
NotRegistered(F),
}
impl<F, T> DispatchRx<F, T> {
pub fn unwrap(self) -> Dispatched<T> {
match self {
DispatchRx::Dispatch(disp) => disp,
DispatchRx::NotRegistered(_) => {
panic!("no BlockingPool was registered for this thread")
}
}
}
}
pub fn dispatch_rx<F, T>(f: F) -> DispatchRx<F, T>
where F: FnOnce() -> T + Send + 'static,
T: Send + 'static
{
POOL.with(|p| {
if let Some(pool) = p.borrow().as_ref() {
let (tx, rx) = oneshot::channel();
pool.spawn(Box::new(|| {
tx.send(f()).ok();
}));
DispatchRx::Dispatch(Dispatched(rx))
} else {
DispatchRx::NotRegistered(f)
}
})
}
#[derive(Debug)]
pub struct Dispatched<T>(oneshot::Receiver<T>);
impl<T> Future for Dispatched<T> {
type Output = Result<T, Canceled>;
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>)
-> Poll<Self::Output>
{
match Future::poll(Pin::new(&mut self.0), cx) {
Poll::Pending => Poll::Pending,
Poll::Ready(Ok(v)) => Poll::Ready(Ok(v)),
Poll::Ready(Err(_)) => Poll::Ready(Err(Canceled))
}
}
}