Skip to content

Commit 7e70a49

Browse files
committed
feat: add tokio::NamedTask util
1 parent 0627957 commit 7e70a49

File tree

4 files changed

+185
-0
lines changed

4 files changed

+185
-0
lines changed

Cargo.lock

Lines changed: 141 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

Cargo.toml

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,11 +14,13 @@ disallowed_methods = "warn"
1414

1515
[features]
1616
default = []
17+
tokio = ["dep:tokio"]
1718
tracing = ["dep:const_format", "dep:tracing", "dep:tracing-appender", "dep:tracing-subscriber"]
1819
version = ["dep:const_format"]
1920

2021
[dependencies]
2122
const_format = { version = "0.2.32", optional = true }
23+
tokio = { version = "1.0", features = ["rt"], optional = true }
2224
tracing = { version = "0.1.40", optional = true }
2325
tracing-appender = { version = "0.2.3", optional = true }
2426
tracing-subscriber = { version = "0.3.18", features = ["env-filter", "json"], optional = true }

src/lib.rs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
pub mod fs;
22
#[cfg(feature = "tracing")]
3+
pub mod tokio;
4+
#[cfg(feature = "tracing")]
35
pub mod tracing;
46
#[cfg(feature = "version")]
57
pub mod version;

src/tokio.rs

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
use std::future::Future;
2+
use std::pin::Pin;
3+
4+
use tokio::task::JoinError;
5+
6+
/// A wrapper around a [tokio::task::JoinHandle] that attaches a name.
7+
///
8+
/// This enables a parent task to await all children simultaneously but still
9+
/// determine what child has exited for logging/diagnosis purposes.
10+
#[derive(Debug)]
11+
pub struct NamedTask<Ret = (), Id = String>
12+
where
13+
Id: Clone + Unpin,
14+
{
15+
task: Pin<Box<tokio::task::JoinHandle<Ret>>>,
16+
id: Id,
17+
}
18+
19+
impl<R, I> NamedTask<R, I>
20+
where
21+
I: Clone + Unpin,
22+
{
23+
pub fn new(task: tokio::task::JoinHandle<R>, id: I) -> Self {
24+
NamedTask { task: Box::pin(task), id }
25+
}
26+
}
27+
28+
impl<R, I> Future for NamedTask<R, I>
29+
where
30+
I: Clone + Unpin,
31+
{
32+
type Output = (I, Result<R, JoinError>);
33+
34+
fn poll(
35+
mut self: Pin<&mut Self>,
36+
cx: &mut std::task::Context<'_>,
37+
) -> std::task::Poll<Self::Output> {
38+
self.task.as_mut().poll(cx).map(|v| (self.id.clone(), v))
39+
}
40+
}

0 commit comments

Comments
 (0)