use crate::global::GlobalExecutor;
use crate::{
AbortableJoinHandle, CommunicationTask, Executor, ExecutorBlocking, JoinHandle,
UnboundedCommunicationTask,
};
use futures::channel::mpsc::{Receiver, UnboundedReceiver};
use std::future::Future;
use std::pin::Pin;
use std::task::{Context, Poll};
const EXECUTOR: GlobalExecutor = GlobalExecutor;
pub fn spawn<F>(future: F) -> JoinHandle<F::Output>
where
F: Future + Send + 'static,
F::Output: Send + 'static,
{
EXECUTOR.spawn(future)
}
pub fn spawn_blocking<F, T>(future: F) -> JoinHandle<T>
where
F: FnOnce() -> T + Send + 'static,
T: Send + 'static,
{
EXECUTOR.spawn_blocking(future)
}
pub fn spawn_abortable<F>(future: F) -> AbortableJoinHandle<F::Output>
where
F: Future + Send + 'static,
F::Output: Send + 'static,
{
EXECUTOR.spawn_abortable(future)
}
pub fn dispatch<F>(future: F)
where
F: Future + Send + 'static,
F::Output: Send + 'static,
{
EXECUTOR.dispatch(future);
}
pub fn spawn_coroutine<T, F, Fut>(f: F) -> CommunicationTask<T>
where
F: FnMut(Receiver<T>) -> Fut,
Fut: Future<Output = ()> + Send + 'static,
{
EXECUTOR.spawn_coroutine(f)
}
pub fn spawn_coroutine_with_buffer<T, F, Fut>(buffer: usize, f: F) -> CommunicationTask<T>
where
F: FnMut(Receiver<T>) -> Fut,
Fut: Future<Output = ()> + Send + 'static,
{
EXECUTOR.spawn_coroutine_with_buffer(buffer, f)
}
pub fn spawn_coroutine_with_context<T, F, C, Fut>(context: C, f: F) -> CommunicationTask<T>
where
F: FnMut(C, Receiver<T>) -> Fut,
Fut: Future<Output = ()> + Send + 'static,
{
EXECUTOR.spawn_coroutine_with_context(context, f)
}
pub fn spawn_coroutine_with_buffer_and_context<T, F, C, Fut>(
context: C,
buffer: usize,
f: F,
) -> CommunicationTask<T>
where
F: FnMut(C, Receiver<T>) -> Fut,
Fut: Future<Output = ()> + Send + 'static,
{
EXECUTOR.spawn_coroutine_with_buffer_and_context(context, buffer, f)
}
pub fn spawn_unbounded_coroutine<T, F, Fut>(f: F) -> UnboundedCommunicationTask<T>
where
F: FnMut(UnboundedReceiver<T>) -> Fut,
Fut: Future<Output = ()> + Send + 'static,
{
EXECUTOR.spawn_unbounded_coroutine(f)
}
pub fn spawn_unbounded_coroutine_with_context<T, F, C, Fut>(
context: C,
f: F,
) -> UnboundedCommunicationTask<T>
where
F: FnMut(C, UnboundedReceiver<T>) -> Fut,
Fut: Future<Output = ()> + Send + 'static,
{
EXECUTOR.spawn_unbounded_coroutine_with_context(context, f)
}
#[derive(Default)]
struct Yield {
yielded: bool,
}
impl Future for Yield {
type Output = ();
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<()> {
if self.yielded {
return Poll::Ready(());
}
self.yielded = true;
cx.waker().wake_by_ref();
Poll::Pending
}
}
pub fn yield_now() -> impl Future<Output = ()> {
Yield::default()
}