-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathruntime.rs
More file actions
62 lines (51 loc) · 1.87 KB
/
runtime.rs
File metadata and controls
62 lines (51 loc) · 1.87 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
#[must_use = "Task has to be used. If you want to detach the task, call .detach() on it."]
pub struct TaskHandle<O: Send + 'static>(
// pub struct TaskHandle<F: futures::Future + Send + 'static>(
#[cfg(feature = "tokio")]
pub tokio::task::JoinHandle<O>,
#[cfg(feature = "smol")]
// The error type is dummy as smol::Task future resolves to the result right away,
// but we want to keep the same API with tokio JoinHandle, which returns a Result.
pub smol::Task<Result<O, std::convert::Infallible>>,
);
impl<O: Send + 'static> Future for TaskHandle<O> {
#[cfg(feature = "tokio")]
type Output = Result<O, tokio::task::JoinError>;
#[cfg(feature = "smol")]
type Output = Result<O, std::convert::Infallible>;
fn poll(mut self: std::pin::Pin<&mut Self>, cx: &mut std::task::Context<'_>) -> std::task::Poll<Self::Output> {
std::pin::Pin::new(&mut self.0).poll(cx)
}
}
// impl<F: futures::Future + Send + 'static> TaskHandle<F> {
impl<O: Send + 'static> TaskHandle<O> {
#[cfg(feature = "tokio")]
#[expect(clippy::unused_async, reason = "We want the same API as with smol")]
pub async fn cancel(self) {
self.0.abort();
}
#[cfg(feature = "smol")]
pub async fn cancel(self) {
self.0.cancel().await;
}
pub fn detach(self) {
#[cfg(feature = "smol")]
self.0.detach();
}
}
pub fn spawn_task<F>(f: F) -> TaskHandle<F::Output>
where
F: futures::Future + Send + 'static,
F::Output: Send + 'static,
{
#[cfg(feature = "tokio")]
{ TaskHandle(tokio::spawn(f)) }
#[cfg(feature = "smol")]
{ TaskHandle(smol::spawn(async move { Ok(f.await) } )) }
}
pub fn block_on<T>(future: impl Future<Output = T>) -> T {
#[cfg(feature = "tokio")]
{ tokio::runtime::Runtime::new().expect("Runtime must work").block_on(future) }
#[cfg(feature = "smol")]
{ smol::block_on(future) }
}