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
26where
27 Fut: Future<Output = ()> + Send + 'static,
28{
29 #[cfg(feature = "tokio-rt")]
30 {
31 let handle = tokio::spawn(future);
32 GateTask::new(Some(handle))
33 }
34
35 #[cfg(feature = "smol-rt")]
36 {
37 let handle = smol::spawn(future);
38 GateTask::new(Some(handle))
39 }
40}
41
42pub struct GateTask
43{
44 #[cfg(feature = "tokio-rt")]
45 inner: Option<JoinHandle<()>>,
46
47 #[cfg(feature = "smol-rt")]
48 inner: Option<smol::Task<()>>,
49}
50
51impl GateTask
52{
53 #[cfg(feature = "tokio-rt")]
54 pub fn new(inner: Option<JoinHandle<()>>) -> Self {
55 Self { inner }
56 }
57
58 #[cfg(feature = "smol-rt")]
59 pub fn new(inner: Option<smol::Task<()>>) -> Self {
60 Self { inner }
61 }
62
63 pub async fn cancel(&mut self) {
64 #[cfg(feature = "tokio-rt")]
65 if let Some(handle) = self.inner.take() {
66 handle.abort();
67 }
68
69 #[cfg(feature = "smol-rt")]
70 if let Some(handle) = self.inner.take() {
71 handle.cancel().await;
72 }
73 }
74}