Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Expose nameable future for TaskLocal::scope #3273

Merged
5 changes: 5 additions & 0 deletions tokio/src/task/mod.rs
Expand Up @@ -304,4 +304,9 @@ cfg_rt! {
mod builder;
pub use builder::Builder;
}

/// Task-related futures.
pub mod futures {
pub use super::task_local::TaskLocalFuture;
}
}
33 changes: 26 additions & 7 deletions tokio/src/task/task_local.rs
Expand Up @@ -115,7 +115,7 @@ impl<T: 'static> LocalKey<T> {
/// }).await;
/// # }
/// ```
pub async fn scope<F>(&'static self, value: T, f: F) -> F::Output
pub fn scope<F>(&'static self, value: T, f: F) -> TaskLocalFuture<T, F>
where
F: Future,
{
Expand All @@ -124,7 +124,6 @@ impl<T: 'static> LocalKey<T> {
slot: Some(value),
future: f,
}
.await
}

/// Sets a value `T` as the task-local value for the closure `F`.
Expand Down Expand Up @@ -206,7 +205,31 @@ impl<T: 'static> fmt::Debug for LocalKey<T> {
}

pin_project! {
struct TaskLocalFuture<T: StaticLifetime, F> {
/// A future that sets a value `T` of a task local for the future `F` during
/// its execution.
///
/// The value of the task-local must be `'static` and will be dropped on the
/// completion of the future.
///
/// Created by the function [`LocalKey::scope`](self::LocalKey::scope).
///
/// ### Examples
///
/// ```
/// # async fn dox() {
/// tokio::task_local! {
/// static NUMBER: u32;
/// }
///
/// NUMBER.scope(1, async move {
/// println!("task local value: {}", NUMBER.get());
/// }).await;
/// # }
/// ```
pub struct TaskLocalFuture<T, F>
where
T: 'static
{
local: &'static LocalKey<T>,
slot: Option<T>,
#[pin]
Expand Down Expand Up @@ -252,10 +275,6 @@ impl<T: 'static, F: Future> Future for TaskLocalFuture<T, F> {
}
}

// Required to make `pin_project` happy.
trait StaticLifetime: 'static {}
impl<T: 'static> StaticLifetime for T {}

/// An error returned by [`LocalKey::try_with`](method@LocalKey::try_with).
#[derive(Clone, Copy, Eq, PartialEq)]
pub struct AccessError {
Expand Down