use std::{cell::Cell, future::Future, pin::Pin, task::Context, task::Poll};
thread_local!(
static CALLBACKS: Cell<Option<TaskCallbacks>> = const { Cell::new(None) };
);
#[derive(Copy, Clone, Debug)]
pub struct TaskCallbacks {
pub before: fn() -> Option<*const ()>,
pub enter: fn(*const ()) -> *const (),
pub exit: fn(*const ()),
pub after: fn(*const ()),
}
pub(crate) fn set_callbacks(cbs: Option<TaskCallbacks>) {
CALLBACKS.set(cbs);
}
pub(crate) struct Data {
cbs: TaskCallbacks,
ptr: *const (),
}
impl Data {
pub(crate) fn load() -> Option<Data> {
let cbs = CALLBACKS.get()?;
(cbs.before)().map(|ptr| Data { cbs, ptr })
}
pub(crate) fn run<F, R>(&mut self, f: F) -> R
where
F: FnOnce() -> R,
{
struct Exit(fn(*const ()), *const ());
impl Drop for Exit {
fn drop(&mut self) {
(self.0)(self.1);
}
}
let _exit = Exit(self.cbs.exit, (self.cbs.enter)(self.ptr));
f()
}
}
pub(crate) fn wrap<F: Future>(fut: F) -> impl Future<Output = F::Output> {
let mut data = Data::load();
async move {
let mut f = std::pin::pin!(fut);
std::future::poll_fn(|cx| match data.as_mut() {
Some(data) => data.run(|| f.as_mut().poll(cx)),
None => f.as_mut().poll(cx),
})
.await
}
}
impl Drop for Data {
fn drop(&mut self) {
(self.cbs.after)(self.ptr);
}
}
#[track_caller]
pub fn spawn_sendable<F>(fut: F) -> SendableJoinHandle<F::Output>
where
F: Future + 'static,
F::Output: Send,
{
let (tx, rx) = oneshot::async_channel();
let (cancel, canceled) = oneshot::async_channel::<()>();
crate::spawn_detached(async move {
let output = {
let mut fut = std::pin::pin!(fut);
let mut canceled = Some(canceled);
std::future::poll_fn(|cx| {
if let Some(rx) = &mut canceled {
match Pin::new(rx).poll(cx) {
Poll::Ready(Ok(())) => return Poll::Ready(None),
Poll::Ready(Err(_)) => canceled = None,
Poll::Pending => {}
}
}
fut.as_mut().poll(cx).map(Some)
})
.await
};
if let Some(output) = output {
let _ = tx.send(output);
}
});
SendableJoinHandle {
rx,
cancel: Some(cancel),
cancel_on_drop: false,
}
}
#[derive(Debug)]
pub struct SendableJoinHandle<T> {
rx: oneshot::AsyncReceiver<T>,
cancel: Option<oneshot::Sender<()>>,
cancel_on_drop: bool,
}
impl<T> SendableJoinHandle<T> {
#[must_use]
pub fn cancel_on_drop(mut self) -> Self {
self.cancel_on_drop = true;
self
}
pub fn cancel(mut self) {
self.cancel_on_drop = true;
}
pub fn is_finished(&self) -> bool {
self.rx.has_message() || self.rx.is_closed()
}
}
impl<T> Drop for SendableJoinHandle<T> {
fn drop(&mut self) {
if self.cancel_on_drop
&& let Some(cancel) = self.cancel.take()
{
let _ = cancel.send(());
}
}
}
impl<T> Future for SendableJoinHandle<T> {
type Output = Result<T, crate::JoinError>;
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
Pin::new(&mut self.rx)
.poll(cx)
.map(|result| result.map_err(|_| crate::JoinError))
}
}
#[cfg(test)]
#[path = "../tests/unit/task.rs"]
mod tests;