From c6fbb9aeb1f8f52055d0fc506f8ac2ffac700bfe Mon Sep 17 00:00:00 2001 From: Moritz Gunz Date: Thu, 8 Jul 2021 12:54:31 +0200 Subject: [PATCH] task: expose nameable future for TaskLocal::scope (#3273) --- tokio/src/task/mod.rs | 5 +++++ tokio/src/task/task_local.rs | 33 ++++++++++++++++++++++++++------- 2 files changed, 31 insertions(+), 7 deletions(-) diff --git a/tokio/src/task/mod.rs b/tokio/src/task/mod.rs index ae4c35c9ce8..ea9878736db 100644 --- a/tokio/src/task/mod.rs +++ b/tokio/src/task/mod.rs @@ -304,4 +304,9 @@ cfg_rt! { mod builder; pub use builder::Builder; } + + /// Task-related futures. + pub mod futures { + pub use super::task_local::TaskLocalFuture; + } } diff --git a/tokio/src/task/task_local.rs b/tokio/src/task/task_local.rs index 6571ffd7b8b..b55c6abc470 100644 --- a/tokio/src/task/task_local.rs +++ b/tokio/src/task/task_local.rs @@ -115,7 +115,7 @@ impl LocalKey { /// }).await; /// # } /// ``` - pub async fn scope(&'static self, value: T, f: F) -> F::Output + pub fn scope(&'static self, value: T, f: F) -> TaskLocalFuture where F: Future, { @@ -124,7 +124,6 @@ impl LocalKey { slot: Some(value), future: f, } - .await } /// Sets a value `T` as the task-local value for the closure `F`. @@ -206,7 +205,31 @@ impl fmt::Debug for LocalKey { } pin_project! { - struct TaskLocalFuture { + /// 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 + where + T: 'static + { local: &'static LocalKey, slot: Option, #[pin] @@ -252,10 +275,6 @@ impl Future for TaskLocalFuture { } } -// Required to make `pin_project` happy. -trait StaticLifetime: 'static {} -impl StaticLifetime for T {} - /// An error returned by [`LocalKey::try_with`](method@LocalKey::try_with). #[derive(Clone, Copy, Eq, PartialEq)] pub struct AccessError {