1use std::future::Future;
2
3#[cfg(feature = "tokio-rt")]
4use tokio::task::JoinHandle;
5
6#[cfg(feature = "smol-rt")]
7use smol::Task;
8
9pub fn spawn_worker<Fut>(future: Fut)
10where
11 Fut: Future + Send + 'static,
12 Fut::Output: Send + 'static,
13{
14 #[cfg(feature = "tokio-rt")]
15 {
16 tokio::spawn(future);
17 }
18
19 #[cfg(feature = "smol-rt")]
20 {
21 smol::spawn(future).detach();
22 }
23}
24
25pub fn spawn_server<Fut>(future: Fut) -> GateTask<Fut>
26where
27 Fut: Future + Send + 'static,
28 Fut::Output: Send + 'static,
29{
30 #[cfg(feature = "tokio-rt")]
31 {
32 let handle = tokio::spawn(future);
33 GateTask::new(Some(handle))
34 }
35
36 #[cfg(feature = "smol-rt")]
37 {
38 let handle = smol::spawn(future);
39 GateTask::new(Some(handle))
40 }
41}
42
43pub struct GateTask<F>
44 where F: Future {
45 #[cfg(feature = "tokio-rt")]
46 inner: Option<JoinHandle<F::Output>>,
47
48 #[cfg(feature = "smol-rt")]
49 inner: Option<smol::Task<F::Output>>,
50}
51
52impl<F> GateTask<F>
53where
54 F: Future + Send + 'static,
55 F::Output: Send + 'static,
56{
57 #[cfg(feature = "tokio-rt")]
58 pub fn new(inner: Option<JoinHandle<F::Output>>) -> Self {
59 Self { inner }
60 }
61
62 #[cfg(feature = "smol-rt")]
63 pub fn new(inner: Option<smol::Task<F::Output>>) -> Self {
64 Self { inner }
65 }
66
67 pub async fn cancel(&mut self) {
68 #[cfg(feature = "tokio-rt")]
69 if let Some(handle) = self.inner.take() {
70 handle.abort();
71 }
72
73 #[cfg(feature = "smol-rt")]
74 if let Some(handle) = self.inner.take() {
75 handle.cancel().await;
76 }
77 }
78}