karyon_core/async_runtime/
task.rs

1use std::future::Future;
2use std::pin::Pin;
3use std::task::{Context, Poll};
4
5use crate::error::Error;
6
7pub struct Task<T> {
8    #[cfg(feature = "smol")]
9    inner_task: smol::Task<T>,
10    #[cfg(feature = "tokio")]
11    inner_task: tokio::task::JoinHandle<T>,
12}
13
14impl<T> Task<T> {
15    pub async fn cancel(self) {
16        #[cfg(feature = "smol")]
17        self.inner_task.cancel().await;
18        #[cfg(feature = "tokio")]
19        self.inner_task.abort();
20    }
21}
22
23impl<T> Future for Task<T> {
24    type Output = Result<T, Error>;
25
26    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
27        #[cfg(feature = "smol")]
28        let result = smol::Task::poll(Pin::new(&mut self.inner_task), cx);
29        #[cfg(feature = "tokio")]
30        let result = tokio::task::JoinHandle::poll(Pin::new(&mut self.inner_task), cx);
31
32        #[cfg(feature = "smol")]
33        return result.map(Ok);
34
35        #[cfg(feature = "tokio")]
36        return result.map_err(|e| e.into());
37    }
38}
39
40#[cfg(feature = "smol")]
41impl<T> From<smol::Task<T>> for Task<T> {
42    fn from(t: smol::Task<T>) -> Task<T> {
43        Task { inner_task: t }
44    }
45}
46
47#[cfg(feature = "tokio")]
48impl<T> From<tokio::task::JoinHandle<T>> for Task<T> {
49    fn from(t: tokio::task::JoinHandle<T>) -> Task<T> {
50        Task { inner_task: t }
51    }
52}