karyon_core/async_runtime/
task.rs1use 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 pub fn detach(self) {
25 #[cfg(feature = "smol")]
26 self.inner_task.detach();
27 #[cfg(feature = "tokio")]
28 drop(self.inner_task);
29 }
30}
31
32impl<T> Future for Task<T> {
33 type Output = Result<T, Error>;
34
35 fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
36 #[cfg(feature = "smol")]
37 let result = smol::Task::poll(Pin::new(&mut self.inner_task), cx);
38 #[cfg(feature = "tokio")]
39 let result = tokio::task::JoinHandle::poll(Pin::new(&mut self.inner_task), cx);
40
41 #[cfg(feature = "smol")]
42 return result.map(Ok);
43
44 #[cfg(feature = "tokio")]
45 return result.map_err(|e| e.into());
46 }
47}
48
49#[cfg(feature = "smol")]
50impl<T> From<smol::Task<T>> for Task<T> {
51 fn from(t: smol::Task<T>) -> Task<T> {
52 Task { inner_task: t }
53 }
54}
55
56#[cfg(feature = "tokio")]
57impl<T> From<tokio::task::JoinHandle<T>> for Task<T> {
58 fn from(t: tokio::task::JoinHandle<T>) -> Task<T> {
59 Task { inner_task: t }
60 }
61}