std/thread/local.rs
1//! Thread local storage
2
3#![unstable(feature = "thread_local_internals", issue = "none")]
4
5use crate::cell::{Cell, RefCell};
6use crate::error::Error;
7use crate::fmt;
8
9/// A thread local storage (TLS) key which owns its contents.
10///
11/// This key uses the fastest implementation available on the target platform.
12/// It is instantiated with the [`thread_local!`] macro and the
13/// primary method is the [`with`] method, though there are helpers to make
14/// working with [`Cell`] types easier.
15///
16/// The [`with`] method yields a reference to the contained value which cannot
17/// outlive the current thread or escape the given closure.
18///
19/// [`thread_local!`]: crate::thread_local
20///
21/// # Initialization and Destruction
22///
23/// Initialization is dynamically performed on the first call to a setter (e.g.
24/// [`with`]) within a thread, and values that implement [`Drop`] get
25/// destructed when a thread exits. Some platform-specific caveats apply, which
26/// are explained below.
27/// Note that, should the destructor panic, the whole process will be [aborted].
28/// On platforms where initialization requires memory allocation, this is
29/// performed directly through [`System`], allowing the [global allocator]
30/// to make use of thread local storage.
31///
32/// A `LocalKey`'s initializer cannot recursively depend on itself. Using a
33/// `LocalKey` in this way may cause panics, aborts, or infinite recursion on
34/// the first call to `with`.
35///
36/// [`System`]: crate::alloc::System
37/// [global allocator]: crate::alloc
38/// [aborted]: crate::process::abort
39///
40/// # Single-thread Synchronization
41///
42/// Though there is no potential race with other threads, it is still possible to
43/// obtain multiple references to the thread-local data in different places on
44/// the call stack. For this reason, only shared (`&T`) references may be obtained.
45///
46/// To allow obtaining an exclusive mutable reference (`&mut T`), typically a
47/// [`Cell`] or [`RefCell`] is used (see the [`std::cell`] for more information
48/// on how exactly this works). To make this easier there are specialized
49/// implementations for [`LocalKey<Cell<T>>`] and [`LocalKey<RefCell<T>>`].
50///
51/// [`std::cell`]: `crate::cell`
52/// [`LocalKey<Cell<T>>`]: struct.LocalKey.html#impl-LocalKey<Cell<T>>
53/// [`LocalKey<RefCell<T>>`]: struct.LocalKey.html#impl-LocalKey<RefCell<T>>
54///
55///
56/// # Examples
57///
58/// ```
59/// use std::cell::Cell;
60/// use std::thread;
61///
62/// // explicit `const {}` block enables more efficient initialization
63/// thread_local!(static FOO: Cell<u32> = const { Cell::new(1) });
64///
65/// assert_eq!(FOO.get(), 1);
66/// FOO.set(2);
67///
68/// // each thread starts out with the initial value of 1
69/// let t = thread::spawn(move || {
70/// assert_eq!(FOO.get(), 1);
71/// FOO.set(3);
72/// });
73///
74/// // wait for the thread to complete and bail out on panic
75/// t.join().unwrap();
76///
77/// // we retain our original value of 2 despite the child thread
78/// assert_eq!(FOO.get(), 2);
79/// ```
80///
81/// # Platform-specific behavior
82///
83/// Note that a "best effort" is made to ensure that destructors for types
84/// stored in thread local storage are run, but not all platforms can guarantee
85/// that destructors will be run for all types in thread local storage. For
86/// example, there are a number of known caveats where destructors are not run:
87///
88/// 1. On Unix systems when pthread-based TLS is being used, destructors will
89/// not be run for TLS values on the main thread when it exits. Note that the
90/// application will exit immediately after the main thread exits as well.
91/// 2. On all platforms it's possible for TLS to re-initialize other TLS slots
92/// during destruction. Some platforms ensure that this cannot happen
93/// infinitely by preventing re-initialization of any slot that has been
94/// destroyed, but not all platforms have this guard. Those platforms that do
95/// not guard typically have a synthetic limit after which point no more
96/// destructors are run.
97/// 3. When the process exits on Windows systems, TLS destructors may only be
98/// run on the thread that causes the process to exit. This is because the
99/// other threads may be forcibly terminated.
100///
101/// TLS destructors may be leaked if a thread exits while [converted into a fiber],
102/// or if Rust TLS destructor support is first needed while running in a fiber.
103///
104/// If a process loads a Rust `cdylib`, it must not cause the Rust TLS destructor support
105/// to be initialized for the first time during process shutdown.
106///
107/// When dynamically unloading a Rust `cdylib`, pending TLS destructors may run
108/// during the unload or may be leaked.
109///
110/// [converted into a fiber]: https://learn.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-convertthreadtofiber
111/// [loader lock]: https://docs.microsoft.com/en-us/windows/win32/dlls/dynamic-link-library-best-practices
112/// [`with`]: LocalKey::with
113#[cfg_attr(not(test), rustc_diagnostic_item = "LocalKey")]
114#[stable(feature = "rust1", since = "1.0.0")]
115pub struct LocalKey<T: 'static> {
116 // This outer `LocalKey<T>` type is what's going to be stored in statics,
117 // but actual data inside will sometimes be tagged with #[thread_local].
118 // It's not valid for a true static to reference a #[thread_local] static,
119 // so we get around that by exposing an accessor through a layer of function
120 // indirection (this thunk).
121 //
122 // Note that the thunk is itself unsafe because the returned lifetime of the
123 // slot where data lives, `'static`, is not actually valid. The lifetime
124 // here is actually slightly shorter than the currently running thread!
125 //
126 // Although this is an extra layer of indirection, it should in theory be
127 // trivially devirtualizable by LLVM because the value of `inner` never
128 // changes and the constant should be readonly within a crate. This mainly
129 // only runs into problems when TLS statics are exported across crates.
130 //
131 // The argument of the function, `init`, can be used to initialize the key for the current
132 // thread: if it is not yet initialized, and if the argument is `Some(&mut Some(val))`, the
133 // inner `val` should be `take`en out and used as the initial value instead of the default.
134 // Also, in that case `inner` *must not* panic. However, it is okay (but potentially
135 // inefficient) for `inner` to ignore `init` and use a default value as long as that is
136 // guaranteed not to panic.
137 inner: fn(/* init */ Option<&mut Option<T>>) -> *const T,
138}
139
140#[stable(feature = "std_debug", since = "1.16.0")]
141impl<T: 'static> fmt::Debug for LocalKey<T> {
142 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
143 f.debug_struct("LocalKey").finish_non_exhaustive()
144 }
145}
146
147#[doc(hidden)]
148#[allow_internal_unstable(thread_local_internals)]
149#[unstable(feature = "thread_local_internals", issue = "none")]
150#[rustc_macro_transparency = "semiopaque"]
151pub macro thread_local_process_attrs {
152
153 // Parse `cfg_attr` to figure out whether it's a `rustc_align_static`.
154 // Each `cfg_attr` can have zero or more attributes on the RHS, and can be nested.
155
156 // finished parsing the `cfg_attr`, it had no `rustc_align_static`
157 (
158 [] [$(#[$($prev_other_attrs:tt)*])*];
159 @processing_cfg_attr { pred: ($($predicate:tt)*), rhs: [] };
160 [$($prev_align_attrs_ret:tt)*] [$($prev_other_attrs_ret:tt)*];
161 $($rest:tt)*
162 ) => (
163 $crate::thread::local_impl::thread_local_process_attrs!(
164 [$($prev_align_attrs_ret)*] [$($prev_other_attrs_ret)* #[cfg_attr($($predicate)*, $($($prev_other_attrs)*),*)]];
165 $($rest)*
166 );
167 ),
168
169 // finished parsing the `cfg_attr`, it had nothing but `rustc_align_static`
170 (
171 [$(#[$($prev_align_attrs:tt)*])+] [];
172 @processing_cfg_attr { pred: ($($predicate:tt)*), rhs: [] };
173 [$($prev_align_attrs_ret:tt)*] [$($prev_other_attrs_ret:tt)*];
174 $($rest:tt)*
175 ) => (
176 $crate::thread::local_impl::thread_local_process_attrs!(
177 [$($prev_align_attrs_ret)* #[cfg_attr($($predicate)*, $($($prev_align_attrs)*),+)]] [$($prev_other_attrs_ret)*];
178 $($rest)*
179 );
180 ),
181
182 // finished parsing the `cfg_attr`, it had a mix of `rustc_align_static` and other attrs
183 (
184 [$(#[$($prev_align_attrs:tt)*])+] [$(#[$($prev_other_attrs:tt)*])+];
185 @processing_cfg_attr { pred: ($($predicate:tt)*), rhs: [] };
186 [$($prev_align_attrs_ret:tt)*] [$($prev_other_attrs_ret:tt)*];
187 $($rest:tt)*
188 ) => (
189 $crate::thread::local_impl::thread_local_process_attrs!(
190 [$($prev_align_attrs_ret)* #[cfg_attr($($predicate)*, $($($prev_align_attrs)*),+)]] [$($prev_other_attrs_ret)* #[cfg_attr($($predicate)*, $($($prev_other_attrs)*),+)]];
191 $($rest)*
192 );
193 ),
194
195 // it's a `rustc_align_static`
196 (
197 [$($prev_align_attrs:tt)*] [$($prev_other_attrs:tt)*];
198 @processing_cfg_attr { pred: ($($predicate:tt)*), rhs: [rustc_align_static($($align_static_args:tt)*) $(, $($attr_rhs:tt)*)?] };
199 $($rest:tt)*
200 ) => (
201 $crate::thread::local_impl::thread_local_process_attrs!(
202 [$($prev_align_attrs)* #[rustc_align_static($($align_static_args)*)]] [$($prev_other_attrs)*];
203 @processing_cfg_attr { pred: ($($predicate)*), rhs: [$($($attr_rhs)*)?] };
204 $($rest)*
205 );
206 ),
207
208 // it's a nested `cfg_attr(..., ...)`; recurse into RHS
209 (
210 [$($prev_align_attrs:tt)*] [$($prev_other_attrs:tt)*];
211 @processing_cfg_attr { pred: ($($predicate:tt)*), rhs: [cfg_attr($cfg_lhs:expr, $($cfg_rhs:tt)*) $(, $($attr_rhs:tt)*)?] };
212 $($rest:tt)*
213 ) => (
214 $crate::thread::local_impl::thread_local_process_attrs!(
215 [] [];
216 @processing_cfg_attr { pred: ($cfg_lhs), rhs: [$($cfg_rhs)*] };
217 [$($prev_align_attrs)*] [$($prev_other_attrs)*];
218 @processing_cfg_attr { pred: ($($predicate)*), rhs: [$($($attr_rhs)*)?] };
219 $($rest)*
220 );
221 ),
222
223 // it's some other attribute
224 (
225 [$($prev_align_attrs:tt)*] [$($prev_other_attrs:tt)*];
226 @processing_cfg_attr { pred: ($($predicate:tt)*), rhs: [$meta:meta $(, $($attr_rhs:tt)*)?] };
227 $($rest:tt)*
228 ) => (
229 $crate::thread::local_impl::thread_local_process_attrs!(
230 [$($prev_align_attrs)*] [$($prev_other_attrs)* #[$meta]];
231 @processing_cfg_attr { pred: ($($predicate)*), rhs: [$($($attr_rhs)*)?] };
232 $($rest)*
233 );
234 ),
235
236
237 // Separate attributes into `rustc_align_static` and everything else:
238
239 // `rustc_align_static` attribute
240 ([$($prev_align_attrs:tt)*] [$($prev_other_attrs:tt)*]; #[rustc_align_static $($attr_rest:tt)*] $($rest:tt)*) => (
241 $crate::thread::local_impl::thread_local_process_attrs!(
242 [$($prev_align_attrs)* #[rustc_align_static $($attr_rest)*]] [$($prev_other_attrs)*];
243 $($rest)*
244 );
245 ),
246
247 // `cfg_attr(..., ...)` attribute; parse it
248 ([$($prev_align_attrs:tt)*] [$($prev_other_attrs:tt)*]; #[cfg_attr($cfg_pred:expr, $($cfg_rhs:tt)*)] $($rest:tt)*) => (
249 $crate::thread::local_impl::thread_local_process_attrs!(
250 [] [];
251 @processing_cfg_attr { pred: ($cfg_pred), rhs: [$($cfg_rhs)*] };
252 [$($prev_align_attrs)*] [$($prev_other_attrs)*];
253 $($rest)*
254 );
255 ),
256
257 // doc comment not followed by any other attributes; process it all at once to avoid blowing recursion limit
258 ([$($prev_align_attrs:tt)*] [$($prev_other_attrs:tt)*]; $(#[doc $($doc_rhs:tt)*])+ $vis:vis static $($rest:tt)*) => (
259 $crate::thread::local_impl::thread_local_process_attrs!(
260 [$($prev_align_attrs)*] [$($prev_other_attrs)* $(#[doc $($doc_rhs)*])+];
261 $vis static $($rest)*
262 );
263 ),
264
265 // 8 lines of doc comment; process them all at once to avoid blowing recursion limit
266 ([$($prev_align_attrs:tt)*] [$($prev_other_attrs:tt)*];
267 #[doc $($doc_rhs_1:tt)*] #[doc $($doc_rhs_2:tt)*] #[doc $($doc_rhs_3:tt)*] #[doc $($doc_rhs_4:tt)*]
268 #[doc $($doc_rhs_5:tt)*] #[doc $($doc_rhs_6:tt)*] #[doc $($doc_rhs_7:tt)*] #[doc $($doc_rhs_8:tt)*]
269 $($rest:tt)*) => (
270 $crate::thread::local_impl::thread_local_process_attrs!(
271 [$($prev_align_attrs)*] [$($prev_other_attrs)*
272 #[doc $($doc_rhs_1)*] #[doc $($doc_rhs_2)*] #[doc $($doc_rhs_3)*] #[doc $($doc_rhs_4)*]
273 #[doc $($doc_rhs_5)*] #[doc $($doc_rhs_6)*] #[doc $($doc_rhs_7)*] #[doc $($doc_rhs_8)*]];
274 $($rest)*
275 );
276 ),
277
278 // other attribute
279 ([$($prev_align_attrs:tt)*] [$($prev_other_attrs:tt)*]; #[$($attr:tt)*] $($rest:tt)*) => (
280 $crate::thread::local_impl::thread_local_process_attrs!(
281 [$($prev_align_attrs)*] [$($prev_other_attrs)* #[$($attr)*]];
282 $($rest)*
283 );
284 ),
285
286
287 // Delegate to `thread_local_inner` once attributes are fully categorized:
288
289 // process `const` declaration and recurse
290 ([$($align_attrs:tt)*] [$($other_attrs:tt)*]; $vis:vis static $name:ident: $t:ty = const $init:block $(; $($($rest:tt)+)?)?) => (
291 $($other_attrs)* $vis const $name: $crate::thread::LocalKey<$t> =
292 $crate::thread::local_impl::thread_local_inner!(@key $t, $($align_attrs)*, const $init);
293
294 $($($crate::thread::local_impl::thread_local_process_attrs!([] []; $($rest)+);)?)?
295 ),
296
297 // process non-`const` declaration and recurse
298 ([$($align_attrs:tt)*] [$($other_attrs:tt)*]; $vis:vis static $name:ident: $t:ty = $init:expr $(; $($($rest:tt)+)?)?) => (
299 $($other_attrs)* $vis const $name: $crate::thread::LocalKey<$t> =
300 $crate::thread::local_impl::thread_local_inner!(@key $t, $($align_attrs)*, $init);
301
302 $($($crate::thread::local_impl::thread_local_process_attrs!([] []; $($rest)+);)?)?
303 ),
304}
305
306/// Declare a new thread local storage key of type [`std::thread::LocalKey`].
307///
308/// # Syntax
309///
310/// The macro wraps any number of static declarations and makes them thread local.
311/// Publicity and attributes for each static are allowed. Example:
312///
313/// ```
314/// use std::cell::{Cell, RefCell};
315///
316/// thread_local! {
317/// pub static FOO: Cell<u32> = const { Cell::new(1) };
318///
319/// static BAR: RefCell<Vec<f32>> = RefCell::new(vec![1.0, 2.0]);
320/// }
321///
322/// assert_eq!(FOO.get(), 1);
323/// BAR.with_borrow(|v| assert_eq!(v[1], 2.0));
324/// ```
325///
326/// Note that only shared references (`&T`) to the inner data may be obtained, so a
327/// type such as [`Cell`] or [`RefCell`] is typically used to allow mutating access.
328///
329/// This macro supports a special `const {}` syntax that can be used
330/// when the initialization expression can be evaluated as a constant.
331/// This can enable a more efficient thread local implementation that
332/// can avoid lazy initialization. For types that do not
333/// [need to be dropped][crate::mem::needs_drop], this can enable an
334/// even more efficient implementation that does not need to
335/// track any additional state.
336///
337/// ```
338/// use std::cell::RefCell;
339///
340/// thread_local! {
341/// pub static FOO: RefCell<Vec<u32>> = const { RefCell::new(Vec::new()) };
342/// }
343///
344/// FOO.with_borrow(|v| assert_eq!(v.len(), 0));
345/// ```
346///
347/// See [`LocalKey` documentation][`std::thread::LocalKey`] for more
348/// information.
349///
350/// [`std::thread::LocalKey`]: crate::thread::LocalKey
351#[macro_export]
352#[stable(feature = "rust1", since = "1.0.0")]
353#[cfg_attr(not(test), rustc_diagnostic_item = "thread_local_macro")]
354#[allow_internal_unstable(thread_local_internals)]
355#[rustc_diagnostic_opaque]
356macro_rules! thread_local {
357 () => {};
358
359 ($($tt:tt)+) => {
360 $crate::thread::local_impl::thread_local_process_attrs!([] []; $($tt)+);
361 };
362}
363
364/// An error returned by [`LocalKey::try_with`](struct.LocalKey.html#method.try_with).
365#[stable(feature = "thread_local_try_with", since = "1.26.0")]
366#[non_exhaustive]
367#[derive(Clone, Copy, Eq, PartialEq)]
368pub struct AccessError;
369
370#[ferrocene::prevalidated]
371#[stable(feature = "thread_local_try_with", since = "1.26.0")]
372impl fmt::Debug for AccessError {
373 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
374 f.debug_struct("AccessError").finish()
375 }
376}
377
378#[stable(feature = "thread_local_try_with", since = "1.26.0")]
379impl fmt::Display for AccessError {
380 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
381 fmt::Display::fmt("already destroyed", f)
382 }
383}
384
385#[stable(feature = "thread_local_try_with", since = "1.26.0")]
386impl Error for AccessError {}
387
388// This ensures the panicking code is outlined from `with` for `LocalKey`.
389#[ferrocene::prevalidated]
390#[cfg_attr(not(panic = "immediate-abort"), inline(never))]
391#[track_caller]
392#[cold]
393fn panic_access_error(err: AccessError) -> ! {
394 panic!("cannot access a Thread Local Storage value during or after destruction: {err:?}")
395}
396
397impl<T: 'static> LocalKey<T> {
398 #[doc(hidden)]
399 #[unstable(
400 feature = "thread_local_internals",
401 reason = "recently added to create a key",
402 issue = "none"
403 )]
404 pub const unsafe fn new(inner: fn(Option<&mut Option<T>>) -> *const T) -> LocalKey<T> {
405 LocalKey { inner }
406 }
407
408 /// Acquires a reference to the value in this TLS key.
409 ///
410 /// This will lazily initialize the value if this thread has not referenced
411 /// this key yet.
412 ///
413 /// # Panics
414 ///
415 /// This function will `panic!()` if the key currently has its
416 /// destructor running, and it **may** panic if the destructor has
417 /// previously been run for this thread.
418 ///
419 /// # Examples
420 ///
421 /// ```
422 /// thread_local! {
423 /// pub static STATIC: String = String::from("I am");
424 /// }
425 ///
426 /// assert_eq!(
427 /// STATIC.with(|original_value| format!("{original_value} initialized")),
428 /// "I am initialized",
429 /// );
430 /// ```
431 #[ferrocene::prevalidated]
432 #[stable(feature = "rust1", since = "1.0.0")]
433 pub fn with<F, R>(&'static self, f: F) -> R
434 where
435 F: FnOnce(&T) -> R,
436 {
437 match self.try_with(f) {
438 Ok(r) => r,
439 Err(err) => panic_access_error(err),
440 }
441 }
442
443 /// Acquires a reference to the value in this TLS key.
444 ///
445 /// This will lazily initialize the value if this thread has not referenced
446 /// this key yet. If the key has been destroyed (which may happen if this is called
447 /// in a destructor), this function may return an [`AccessError`].
448 ///
449 /// # Panics
450 ///
451 /// This function will still `panic!()` if the key is uninitialized and the
452 /// key's initializer panics.
453 ///
454 /// # Examples
455 ///
456 /// ```
457 /// thread_local! {
458 /// pub static STATIC: String = String::from("I am");
459 /// }
460 ///
461 /// assert_eq!(
462 /// STATIC.try_with(|original_value| format!("{original_value} initialized")),
463 /// Ok(String::from("I am initialized")),
464 /// );
465 /// ```
466 #[ferrocene::prevalidated]
467 #[stable(feature = "thread_local_try_with", since = "1.26.0")]
468 #[inline]
469 pub fn try_with<F, R>(&'static self, f: F) -> Result<R, AccessError>
470 where
471 F: FnOnce(&T) -> R,
472 {
473 let thread_local = unsafe { (self.inner)(None).as_ref().ok_or(AccessError)? };
474 Ok(f(thread_local))
475 }
476
477 /// Acquires a reference to the value in this TLS key, initializing it with
478 /// `init` if it wasn't already initialized on this thread.
479 ///
480 /// If `init` was used to initialize the thread local variable, `None` is
481 /// passed as the first argument to `f`. If it was already initialized,
482 /// `Some(init)` is passed to `f`.
483 ///
484 /// # Panics
485 ///
486 /// This function will panic if the key currently has its destructor
487 /// running, and it **may** panic if the destructor has previously been run
488 /// for this thread.
489 #[ferrocene::prevalidated]
490 fn initialize_with<F, R>(&'static self, init: T, f: F) -> R
491 where
492 F: FnOnce(Option<T>, &T) -> R,
493 {
494 let mut init = Some(init);
495
496 let reference = unsafe {
497 match (self.inner)(Some(&mut init)).as_ref() {
498 Some(r) => r,
499 None => panic_access_error(AccessError),
500 }
501 };
502
503 f(init, reference)
504 }
505}
506
507impl<T: 'static> LocalKey<Cell<T>> {
508 /// Sets or initializes the contained value.
509 ///
510 /// Unlike the other methods, this will *not* run the lazy initializer of
511 /// the thread local. Instead, it will be directly initialized with the
512 /// given value if it wasn't initialized yet.
513 ///
514 /// # Panics
515 ///
516 /// Panics if the key currently has its destructor running,
517 /// and it **may** panic if the destructor has previously been run for this thread.
518 ///
519 /// # Examples
520 ///
521 /// ```
522 /// use std::cell::Cell;
523 ///
524 /// thread_local! {
525 /// static X: Cell<i32> = panic!("!");
526 /// }
527 ///
528 /// // Calling X.get() here would result in a panic.
529 ///
530 /// X.set(123); // But X.set() is fine, as it skips the initializer above.
531 ///
532 /// assert_eq!(X.get(), 123);
533 /// ```
534 #[ferrocene::prevalidated]
535 #[stable(feature = "local_key_cell_methods", since = "1.73.0")]
536 pub fn set(&'static self, value: T) {
537 self.initialize_with(Cell::new(value), |value, cell| {
538 if let Some(value) = value {
539 // The cell was already initialized, so `value` wasn't used to
540 // initialize it. So we overwrite the current value with the
541 // new one instead.
542 cell.set(value.into_inner());
543 }
544 });
545 }
546
547 /// Returns a copy of the contained value.
548 ///
549 /// This will lazily initialize the value if this thread has not referenced
550 /// this key yet.
551 ///
552 /// # Panics
553 ///
554 /// Panics if the key currently has its destructor running,
555 /// and it **may** panic if the destructor has previously been run for this thread.
556 ///
557 /// # Examples
558 ///
559 /// ```
560 /// use std::cell::Cell;
561 ///
562 /// thread_local! {
563 /// static X: Cell<i32> = const { Cell::new(1) };
564 /// }
565 ///
566 /// assert_eq!(X.get(), 1);
567 /// ```
568 #[stable(feature = "local_key_cell_methods", since = "1.73.0")]
569 pub fn get(&'static self) -> T
570 where
571 T: Copy,
572 {
573 self.with(Cell::get)
574 }
575
576 /// Takes the contained value, leaving `Default::default()` in its place.
577 ///
578 /// This will lazily initialize the value if this thread has not referenced
579 /// this key yet.
580 ///
581 /// # Panics
582 ///
583 /// Panics if the key currently has its destructor running,
584 /// and it **may** panic if the destructor has previously been run for this thread.
585 ///
586 /// # Examples
587 ///
588 /// ```
589 /// use std::cell::Cell;
590 ///
591 /// thread_local! {
592 /// static X: Cell<Option<i32>> = const { Cell::new(Some(1)) };
593 /// }
594 ///
595 /// assert_eq!(X.take(), Some(1));
596 /// assert_eq!(X.take(), None);
597 /// ```
598 #[stable(feature = "local_key_cell_methods", since = "1.73.0")]
599 pub fn take(&'static self) -> T
600 where
601 T: Default,
602 {
603 self.with(Cell::take)
604 }
605
606 /// Replaces the contained value, returning the old value.
607 ///
608 /// This will lazily initialize the value if this thread has not referenced
609 /// this key yet.
610 ///
611 /// # Panics
612 ///
613 /// Panics if the key currently has its destructor running,
614 /// and it **may** panic if the destructor has previously been run for this thread.
615 ///
616 /// # Examples
617 ///
618 /// ```
619 /// use std::cell::Cell;
620 ///
621 /// thread_local! {
622 /// static X: Cell<i32> = const { Cell::new(1) };
623 /// }
624 ///
625 /// assert_eq!(X.replace(2), 1);
626 /// assert_eq!(X.replace(3), 2);
627 /// ```
628 #[stable(feature = "local_key_cell_methods", since = "1.73.0")]
629 #[rustc_confusables("swap")]
630 pub fn replace(&'static self, value: T) -> T {
631 self.with(|cell| cell.replace(value))
632 }
633
634 /// Updates the contained value using a function.
635 ///
636 /// This will lazily initialize the value if this thread has not referenced
637 /// this key yet.
638 ///
639 /// # Panics
640 ///
641 /// Panics if the key currently has its destructor running,
642 /// and it **may** panic if the destructor has previously been run for this thread.
643 ///
644 /// # Examples
645 ///
646 /// ```
647 /// use std::cell::Cell;
648 ///
649 /// thread_local! {
650 /// static X: Cell<i32> = const { Cell::new(5) };
651 /// }
652 ///
653 /// X.update(|x| x + 1);
654 /// assert_eq!(X.get(), 6);
655 /// ```
656 #[stable(feature = "local_key_cell_update", since = "1.99.0")]
657 pub fn update(&'static self, f: impl FnOnce(T) -> T)
658 where
659 T: Copy,
660 {
661 self.with(|cell| cell.update(f))
662 }
663}
664
665impl<T: 'static> LocalKey<RefCell<T>> {
666 /// Acquires a reference to the contained value.
667 ///
668 /// This will lazily initialize the value if this thread has not referenced
669 /// this key yet.
670 ///
671 /// # Panics
672 ///
673 /// Panics if the value is currently mutably borrowed.
674 ///
675 /// Panics if the key currently has its destructor running,
676 /// and it **may** panic if the destructor has previously been run for this thread.
677 ///
678 /// # Examples
679 ///
680 /// ```
681 /// use std::cell::RefCell;
682 ///
683 /// thread_local! {
684 /// static X: RefCell<Vec<i32>> = RefCell::new(Vec::new());
685 /// }
686 ///
687 /// X.with_borrow(|v| assert!(v.is_empty()));
688 /// ```
689 #[stable(feature = "local_key_cell_methods", since = "1.73.0")]
690 pub fn with_borrow<F, R>(&'static self, f: F) -> R
691 where
692 F: FnOnce(&T) -> R,
693 {
694 self.with(|cell| f(&cell.borrow()))
695 }
696
697 /// Acquires a mutable reference to the contained value.
698 ///
699 /// This will lazily initialize the value if this thread has not referenced
700 /// this key yet.
701 ///
702 /// # Panics
703 ///
704 /// Panics if the value is currently borrowed.
705 ///
706 /// Panics if the key currently has its destructor running,
707 /// and it **may** panic if the destructor has previously been run for this thread.
708 ///
709 /// # Examples
710 ///
711 /// ```
712 /// use std::cell::RefCell;
713 ///
714 /// thread_local! {
715 /// static X: RefCell<Vec<i32>> = RefCell::new(Vec::new());
716 /// }
717 ///
718 /// X.with_borrow_mut(|v| v.push(1));
719 ///
720 /// X.with_borrow(|v| assert_eq!(*v, vec![1]));
721 /// ```
722 #[stable(feature = "local_key_cell_methods", since = "1.73.0")]
723 pub fn with_borrow_mut<F, R>(&'static self, f: F) -> R
724 where
725 F: FnOnce(&mut T) -> R,
726 {
727 self.with(|cell| f(&mut cell.borrow_mut()))
728 }
729
730 /// Sets or initializes the contained value.
731 ///
732 /// Unlike the other methods, this will *not* run the lazy initializer of
733 /// the thread local. Instead, it will be directly initialized with the
734 /// given value if it wasn't initialized yet.
735 ///
736 /// # Panics
737 ///
738 /// Panics if the value is currently borrowed.
739 ///
740 /// Panics if the key currently has its destructor running,
741 /// and it **may** panic if the destructor has previously been run for this thread.
742 ///
743 /// # Examples
744 ///
745 /// ```
746 /// use std::cell::RefCell;
747 ///
748 /// thread_local! {
749 /// static X: RefCell<Vec<i32>> = panic!("!");
750 /// }
751 ///
752 /// // Calling X.with() here would result in a panic.
753 ///
754 /// X.set(vec![1, 2, 3]); // But X.set() is fine, as it skips the initializer above.
755 ///
756 /// X.with_borrow(|v| assert_eq!(*v, vec![1, 2, 3]));
757 /// ```
758 #[stable(feature = "local_key_cell_methods", since = "1.73.0")]
759 pub fn set(&'static self, value: T) {
760 self.initialize_with(RefCell::new(value), |value, cell| {
761 if let Some(value) = value {
762 // The cell was already initialized, so `value` wasn't used to
763 // initialize it. So we overwrite the current value with the
764 // new one instead.
765 *cell.borrow_mut() = value.into_inner();
766 }
767 });
768 }
769
770 /// Takes the contained value, leaving `Default::default()` in its place.
771 ///
772 /// This will lazily initialize the value if this thread has not referenced
773 /// this key yet.
774 ///
775 /// # Panics
776 ///
777 /// Panics if the value is currently borrowed.
778 ///
779 /// Panics if the key currently has its destructor running,
780 /// and it **may** panic if the destructor has previously been run for this thread.
781 ///
782 /// # Examples
783 ///
784 /// ```
785 /// use std::cell::RefCell;
786 ///
787 /// thread_local! {
788 /// static X: RefCell<Vec<i32>> = RefCell::new(Vec::new());
789 /// }
790 ///
791 /// X.with_borrow_mut(|v| v.push(1));
792 ///
793 /// let a = X.take();
794 ///
795 /// assert_eq!(a, vec![1]);
796 ///
797 /// X.with_borrow(|v| assert!(v.is_empty()));
798 /// ```
799 #[stable(feature = "local_key_cell_methods", since = "1.73.0")]
800 pub fn take(&'static self) -> T
801 where
802 T: Default,
803 {
804 self.with(RefCell::take)
805 }
806
807 /// Replaces the contained value, returning the old value.
808 ///
809 /// # Panics
810 ///
811 /// Panics if the value is currently borrowed.
812 ///
813 /// Panics if the key currently has its destructor running,
814 /// and it **may** panic if the destructor has previously been run for this thread.
815 ///
816 /// # Examples
817 ///
818 /// ```
819 /// use std::cell::RefCell;
820 ///
821 /// thread_local! {
822 /// static X: RefCell<Vec<i32>> = RefCell::new(Vec::new());
823 /// }
824 ///
825 /// let prev = X.replace(vec![1, 2, 3]);
826 /// assert!(prev.is_empty());
827 ///
828 /// X.with_borrow(|v| assert_eq!(*v, vec![1, 2, 3]));
829 /// ```
830 #[stable(feature = "local_key_cell_methods", since = "1.73.0")]
831 #[rustc_confusables("swap")]
832 pub fn replace(&'static self, value: T) -> T {
833 self.with(|cell| cell.replace(value))
834 }
835}