Skip to content

Commit

Permalink
task: expose nameable future for TaskLocal::scope (#3273)
Browse files Browse the repository at this point in the history
  • Loading branch information
NeoLegends committed Jul 8, 2021
1 parent 5d61c99 commit c6fbb9a
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 7 deletions.
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

0 comments on commit c6fbb9a

Please sign in to comment.