task_local/lib.rs
1//! Task-local storage for asynchronous tasks.
2//!
3//! This crate provides a way to store task-local values across `.await` points.
4//! It was extracted from the `tokio::task_local` module and can be used independently
5//! of the Tokio runtime.
6
7use pin_project_lite::pin_project;
8use std::cell::RefCell;
9use std::error::Error;
10use std::future::Future;
11use std::marker::PhantomPinned;
12use std::pin::Pin;
13use std::task::{Context, Poll};
14use std::{fmt, mem, thread};
15
16/// Declares a new task-local key of type [`LocalKey`].
17///
18/// # Syntax
19///
20/// The macro wraps any number of static declarations and makes them local to the current task.
21/// Publicity and attributes for each static is preserved. For example:
22///
23/// # Examples
24///
25/// ```
26/// # use task_local::task_local;
27/// task_local! {
28/// pub static ONE: u32;
29///
30/// #[allow(unused)]
31/// static TWO: f32;
32/// }
33/// # fn main() {}
34/// ```
35///
36/// See [`LocalKey` documentation][`LocalKey`] for more information.
37#[macro_export]
38macro_rules! task_local {
39 // empty (base case for the recursion)
40 () => {};
41
42 ($(#[$attr:meta])* $vis:vis static $name:ident: $t:ty; $($rest:tt)*) => {
43 $crate::__task_local_inner!($(#[$attr])* $vis $name, $t);
44 $crate::task_local!($($rest)*);
45 };
46
47 ($(#[$attr:meta])* $vis:vis static $name:ident: $t:ty) => {
48 $crate::__task_local_inner!($(#[$attr])* $vis $name, $t);
49 }
50}
51
52#[doc(hidden)]
53#[macro_export]
54macro_rules! __task_local_inner {
55 ($(#[$attr:meta])* $vis:vis $name:ident, $t:ty) => {
56 $(#[$attr])*
57 $vis static $name: $crate::LocalKey<$t> = {
58 std::thread_local! {
59 static __KEY: std::cell::RefCell<Option<$t>> = const { std::cell::RefCell::new(None) };
60 }
61
62 $crate::LocalKey { inner: __KEY }
63 };
64 };
65}
66
67/// A key for task-local data.
68///
69/// This type is generated by the [`task_local!`] macro.
70///
71/// Unlike [`std::thread::LocalKey`], `LocalKey` will
72/// _not_ lazily initialize the value on first access. Instead, the
73/// value is first initialized when the future containing
74/// the task-local is first polled by a futures executor.
75///
76/// # Examples
77///
78/// ```
79/// # async fn dox() {
80/// task_local::task_local! {
81/// static NUMBER: u32;
82/// }
83///
84/// NUMBER.scope(1, async move {
85/// assert_eq!(NUMBER.get(), 1);
86/// }).await;
87///
88/// NUMBER.scope(2, async move {
89/// assert_eq!(NUMBER.get(), 2);
90///
91/// NUMBER.scope(3, async move {
92/// assert_eq!(NUMBER.get(), 3);
93/// }).await;
94/// }).await;
95/// # }
96/// ```
97///
98/// [`std::thread::LocalKey`]: struct@std::thread::LocalKey
99pub struct LocalKey<T: 'static> {
100 #[doc(hidden)]
101 pub inner: thread::LocalKey<RefCell<Option<T>>>,
102}
103
104impl<T: 'static> LocalKey<T> {
105 /// Sets a value `T` as the task-local value for the future `F`.
106 ///
107 /// On completion of `scope`, the task-local will be dropped.
108 ///
109 /// ### Panics
110 ///
111 /// If you poll the returned future inside a call to [`with`] or
112 /// [`try_with`] on the same `LocalKey`, then the call to `poll` will panic.
113 ///
114 /// ### Examples
115 ///
116 /// ```
117 /// # async fn dox() {
118 /// task_local::task_local! {
119 /// static NUMBER: u32;
120 /// }
121 ///
122 /// NUMBER.scope(1, async move {
123 /// println!("task local value: {}", NUMBER.get());
124 /// }).await;
125 /// # }
126 /// ```
127 ///
128 /// [`with`]: fn@Self::with
129 /// [`try_with`]: fn@Self::try_with
130 pub fn scope<F>(&'static self, value: T, f: F) -> TaskLocalFuture<T, F>
131 where
132 F: Future,
133 {
134 TaskLocalFuture {
135 local: self,
136 slot: Some(value),
137 future: Some(f),
138 _pinned: PhantomPinned,
139 }
140 }
141
142 /// Sets a value `T` as the task-local value for the closure `F`.
143 ///
144 /// On completion of `sync_scope`, the task-local will be dropped.
145 ///
146 /// ### Panics
147 ///
148 /// This method panics if called inside a call to [`with`] or [`try_with`]
149 /// on the same `LocalKey`.
150 ///
151 /// ### Examples
152 ///
153 /// ```
154 /// # async fn dox() {
155 /// task_local::task_local! {
156 /// static NUMBER: u32;
157 /// }
158 ///
159 /// NUMBER.sync_scope(1, || {
160 /// println!("task local value: {}", NUMBER.get());
161 /// });
162 /// # }
163 /// ```
164 ///
165 /// [`with`]: fn@Self::with
166 /// [`try_with`]: fn@Self::try_with
167 #[track_caller]
168 pub fn sync_scope<F, R>(&'static self, value: T, f: F) -> R
169 where
170 F: FnOnce() -> R,
171 {
172 let mut value = Some(value);
173 match self.scope_inner(&mut value, f) {
174 Ok(res) => res,
175 Err(err) => err.panic(),
176 }
177 }
178
179 fn scope_inner<F, R>(&'static self, slot: &mut Option<T>, f: F) -> Result<R, ScopeInnerErr>
180 where
181 F: FnOnce() -> R,
182 {
183 struct Guard<'a, T: 'static> {
184 local: &'static LocalKey<T>,
185 slot: &'a mut Option<T>,
186 }
187
188 impl<T: 'static> Drop for Guard<'_, T> {
189 fn drop(&mut self) {
190 // This should not panic.
191 //
192 // We know that the RefCell was not borrowed before the call to
193 // `scope_inner`, so the only way for this to panic is if the
194 // closure has created but not destroyed a RefCell guard.
195 // However, we never give user-code access to the guards, so
196 // there's no way for user-code to forget to destroy a guard.
197 //
198 // The call to `with` also should not panic, since the
199 // thread-local wasn't destroyed when we first called
200 // `scope_inner`, and it shouldn't have gotten destroyed since
201 // then.
202 self.local.inner.with(|inner| {
203 let mut ref_mut = inner.borrow_mut();
204 mem::swap(self.slot, &mut *ref_mut);
205 });
206 }
207 }
208
209 self.inner.try_with(|inner| {
210 inner
211 .try_borrow_mut()
212 .map(|mut ref_mut| mem::swap(slot, &mut *ref_mut))
213 })??;
214
215 let guard = Guard { local: self, slot };
216
217 let res = f();
218
219 drop(guard);
220
221 Ok(res)
222 }
223
224 /// Accesses the current task-local and runs the provided closure.
225 ///
226 /// # Panics
227 ///
228 /// This function will panic if the task local doesn't have a value set.
229 #[track_caller]
230 pub fn with<F, R>(&'static self, f: F) -> R
231 where
232 F: FnOnce(&T) -> R,
233 {
234 match self.try_with(f) {
235 Ok(res) => res,
236 Err(_) => panic!("cannot access a task-local storage value without setting it first"),
237 }
238 }
239
240 /// Accesses the current task-local and runs the provided closure.
241 ///
242 /// If the task-local with the associated key is not present, this
243 /// method will return an `AccessError`. For a panicking variant,
244 /// see `with`.
245 pub fn try_with<F, R>(&'static self, f: F) -> Result<R, AccessError>
246 where
247 F: FnOnce(&T) -> R,
248 {
249 // If called after the thread-local storing the task-local is destroyed,
250 // then we are outside of a closure where the task-local is set.
251 //
252 // Therefore, it is correct to return an AccessError if `try_with`
253 // returns an error.
254 let try_with_res = self.inner.try_with(|v| {
255 // This call to `borrow` cannot panic because no user-defined code
256 // runs while a `borrow_mut` call is active.
257 v.borrow().as_ref().map(f)
258 });
259
260 match try_with_res {
261 Ok(Some(res)) => Ok(res),
262 Ok(None) | Err(_) => Err(AccessError { _private: () }),
263 }
264 }
265}
266
267impl<T: Clone + 'static> LocalKey<T> {
268 /// Returns a copy of the task-local value
269 /// if the task-local value implements `Clone`.
270 ///
271 /// # Panics
272 ///
273 /// This function will panic if the task local doesn't have a value set.
274 #[track_caller]
275 pub fn get(&'static self) -> T {
276 self.with(|v| v.clone())
277 }
278
279 /// Returns a copy of the task-local value
280 /// if the task-local value implements `Clone`.
281 ///
282 /// If the task-local with the associated key is not present, this
283 /// method will return an [AccessError]. For a panicking variant,
284 /// see [get][Self::get].
285 #[track_caller]
286 pub fn try_get(&'static self) -> Result<T, AccessError> {
287 self.try_with(|v| v.clone())
288 }
289}
290
291impl<T: 'static> fmt::Debug for LocalKey<T> {
292 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
293 f.pad("LocalKey { .. }")
294 }
295}
296
297pin_project! {
298 /// A future that sets a value `T` of a task local for the future `F` during
299 /// its execution.
300 ///
301 /// The value of the task-local must be `'static` and will be dropped on the
302 /// completion of the future.
303 ///
304 /// Created by the function [`LocalKey::scope`](self::LocalKey::scope).
305 ///
306 /// ### Examples
307 ///
308 /// ```
309 /// # async fn dox() {
310 /// task_local::task_local! {
311 /// static NUMBER: u32;
312 /// }
313 ///
314 /// NUMBER.scope(1, async move {
315 /// println!("task local value: {}", NUMBER.get());
316 /// }).await;
317 /// # }
318 /// ```
319 pub struct TaskLocalFuture<T, F>
320 where
321 T: 'static,
322 {
323 local: &'static LocalKey<T>,
324 slot: Option<T>,
325 #[pin]
326 future: Option<F>,
327 #[pin]
328 _pinned: PhantomPinned,
329 }
330
331 impl<T: 'static, F> PinnedDrop for TaskLocalFuture<T, F> {
332 fn drop(this: Pin<&mut Self>) {
333 let this = this.project();
334 if mem::needs_drop::<F>() && this.future.is_some() {
335 // Drop the future while the task-local is set, if possible. Otherwise
336 // the future is dropped normally when the `Option<F>` field drops.
337 let mut future = this.future;
338 let _ = this.local.scope_inner(this.slot, || {
339 future.set(None);
340 });
341 }
342 }
343 }
344}
345
346impl<T, F> TaskLocalFuture<T, F>
347where
348 T: 'static,
349{
350 /// Returns the value stored in the task local by this `TaskLocalFuture`.
351 ///
352 /// The function returns:
353 ///
354 /// * `Some(T)` if the task local value exists.
355 /// * `None` if the task local value has already been taken.
356 ///
357 /// Note that this function attempts to take the task local value even if
358 /// the future has not yet completed. In that case, the value will no longer
359 /// be available via the task local after the call to `take_value`.
360 ///
361 /// # Examples
362 ///
363 /// ```
364 /// # async fn dox() {
365 /// task_local::task_local! {
366 /// static KEY: u32;
367 /// }
368 ///
369 /// let fut = KEY.scope(42, async {
370 /// // Do some async work
371 /// });
372 ///
373 /// let mut pinned = Box::pin(fut);
374 ///
375 /// // Complete the TaskLocalFuture
376 /// let _ = pinned.as_mut().await;
377 ///
378 /// // And here, we can take task local value
379 /// let value = pinned.as_mut().take_value();
380 ///
381 /// assert_eq!(value, Some(42));
382 /// # }
383 /// ```
384 pub fn take_value(self: Pin<&mut Self>) -> Option<T> {
385 let this = self.project();
386 this.slot.take()
387 }
388}
389
390impl<T: 'static, F: Future> Future for TaskLocalFuture<T, F> {
391 type Output = F::Output;
392
393 #[track_caller]
394 fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
395 let this = self.project();
396 let mut future_opt = this.future;
397
398 let res = this
399 .local
400 .scope_inner(this.slot, || match future_opt.as_mut().as_pin_mut() {
401 Some(fut) => {
402 let res = fut.poll(cx);
403 if res.is_ready() {
404 future_opt.set(None);
405 }
406 Some(res)
407 }
408 None => None,
409 });
410
411 match res {
412 Ok(Some(res)) => res,
413 Ok(None) => panic!("`TaskLocalFuture` polled after completion"),
414 Err(err) => err.panic(),
415 }
416 }
417}
418
419impl<T: 'static, F> fmt::Debug for TaskLocalFuture<T, F>
420where
421 T: fmt::Debug,
422{
423 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
424 /// Format the Option without Some.
425 struct TransparentOption<'a, T> {
426 value: &'a Option<T>,
427 }
428 impl<T: fmt::Debug> fmt::Debug for TransparentOption<'_, T> {
429 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
430 match self.value.as_ref() {
431 Some(value) => value.fmt(f),
432 // Hitting the None branch should not be possible.
433 None => f.pad("<missing>"),
434 }
435 }
436 }
437
438 f.debug_struct("TaskLocalFuture")
439 .field("value", &TransparentOption { value: &self.slot })
440 .finish()
441 }
442}
443
444/// An error returned by [`LocalKey::try_with`](method@LocalKey::try_with).
445#[derive(Clone, Copy, Eq, PartialEq)]
446pub struct AccessError {
447 _private: (),
448}
449
450impl fmt::Debug for AccessError {
451 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
452 f.debug_struct("AccessError").finish()
453 }
454}
455
456impl fmt::Display for AccessError {
457 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
458 fmt::Display::fmt("task-local value not set", f)
459 }
460}
461
462impl Error for AccessError {}
463
464enum ScopeInnerErr {
465 BorrowError,
466 AccessError,
467}
468
469impl ScopeInnerErr {
470 #[track_caller]
471 fn panic(&self) -> ! {
472 match self {
473 Self::BorrowError => {
474 panic!("cannot enter a task-local scope while the task-local storage is borrowed")
475 }
476 Self::AccessError => panic!(
477 "cannot enter a task-local scope during or after destruction of the underlying thread-local"
478 ),
479 }
480 }
481}
482
483impl From<std::cell::BorrowMutError> for ScopeInnerErr {
484 fn from(_: std::cell::BorrowMutError) -> Self {
485 Self::BorrowError
486 }
487}
488
489impl From<std::thread::AccessError> for ScopeInnerErr {
490 fn from(_: std::thread::AccessError) -> Self {
491 Self::AccessError
492 }
493}