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