rt_gate/
lib.rs

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