Skip to main content

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(#[automatically_derived]
#[doc(hidden)]
#[stable(feature = "thread_local_try_with", since = "1.26.0")]
unsafe impl ::core::clone::TrivialClone for AccessError { }
#[automatically_derived]
#[stable(feature = "thread_local_try_with", since = "1.26.0")]
impl ::core::clone::Clone for AccessError {
    #[inline]
    fn clone(&self) -> Self { *self }
}Clone, #[automatically_derived]
#[stable(feature = "thread_local_try_with", since = "1.26.0")]
impl ::core::marker::Copy for AccessError { }Copy, #[automatically_derived]
#[stable(feature = "thread_local_try_with", since = "1.26.0")]
impl ::core::cmp::Eq for AccessError { }Eq, #[automatically_derived]
#[stable(feature = "thread_local_try_with", since = "1.26.0")]
impl ::core::marker::StructuralPartialEq for AccessError { }
#[automatically_derived]
#[stable(feature = "thread_local_try_with", since = "1.26.0")]
impl ::core::cmp::PartialEq for AccessError {
    #[inline]
    fn eq(&self, other: &Self) -> bool { true }
}PartialEq)]
368pub struct AccessError;
369
370#[stable(feature = "thread_local_try_with", since = "1.26.0")]
371impl fmt::Debug for AccessError {
372    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
373        f.debug_struct("AccessError").finish()
374    }
375}
376
377#[stable(feature = "thread_local_try_with", since = "1.26.0")]
378impl fmt::Display for AccessError {
379    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
380        fmt::Display::fmt("already destroyed", f)
381    }
382}
383
384#[stable(feature = "thread_local_try_with", since = "1.26.0")]
385impl Error for AccessError {}
386
387// This ensures the panicking code is outlined from `with` for `LocalKey`.
388#[cfg_attr(not(panic = "immediate-abort"), inline(never))]
389#[track_caller]
390#[cold]
391fn panic_access_error(err: AccessError) -> ! {
392    {
    ::core::panicking::panic_fmt(format_args!("cannot access a Thread Local Storage value during or after destruction: {0:?}",
            err));
}panic!("cannot access a Thread Local Storage value during or after destruction: {err:?}")
393}
394
395impl<T: 'static> LocalKey<T> {
396    #[doc(hidden)]
397    #[unstable(
398        feature = "thread_local_internals",
399        reason = "recently added to create a key",
400        issue = "none"
401    )]
402    pub const unsafe fn new(inner: fn(Option<&mut Option<T>>) -> *const T) -> LocalKey<T> {
403        LocalKey { inner }
404    }
405
406    /// Acquires a reference to the value in this TLS key.
407    ///
408    /// This will lazily initialize the value if this thread has not referenced
409    /// this key yet.
410    ///
411    /// # Panics
412    ///
413    /// This function will `panic!()` if the key currently has its
414    /// destructor running, and it **may** panic if the destructor has
415    /// previously been run for this thread.
416    ///
417    /// # Examples
418    ///
419    /// ```
420    /// thread_local! {
421    ///     pub static STATIC: String = String::from("I am");
422    /// }
423    ///
424    /// assert_eq!(
425    ///     STATIC.with(|original_value| format!("{original_value} initialized")),
426    ///     "I am initialized",
427    /// );
428    /// ```
429    #[stable(feature = "rust1", since = "1.0.0")]
430    pub fn with<F, R>(&'static self, f: F) -> R
431    where
432        F: FnOnce(&T) -> R,
433    {
434        match self.try_with(f) {
435            Ok(r) => r,
436            Err(err) => panic_access_error(err),
437        }
438    }
439
440    /// Acquires a reference to the value in this TLS key.
441    ///
442    /// This will lazily initialize the value if this thread has not referenced
443    /// this key yet. If the key has been destroyed (which may happen if this is called
444    /// in a destructor), this function may return an [`AccessError`].
445    ///
446    /// # Panics
447    ///
448    /// This function will still `panic!()` if the key is uninitialized and the
449    /// key's initializer panics.
450    ///
451    /// # Examples
452    ///
453    /// ```
454    /// thread_local! {
455    ///     pub static STATIC: String = String::from("I am");
456    /// }
457    ///
458    /// assert_eq!(
459    ///     STATIC.try_with(|original_value| format!("{original_value} initialized")),
460    ///     Ok(String::from("I am initialized")),
461    /// );
462    /// ```
463    #[stable(feature = "thread_local_try_with", since = "1.26.0")]
464    #[inline]
465    pub fn try_with<F, R>(&'static self, f: F) -> Result<R, AccessError>
466    where
467        F: FnOnce(&T) -> R,
468    {
469        let thread_local = unsafe { (self.inner)(None).as_ref().ok_or(AccessError)? };
470        Ok(f(thread_local))
471    }
472
473    /// Acquires a reference to the value in this TLS key, initializing it with
474    /// `init` if it wasn't already initialized on this thread.
475    ///
476    /// If `init` was used to initialize the thread local variable, `None` is
477    /// passed as the first argument to `f`. If it was already initialized,
478    /// `Some(init)` is passed to `f`.
479    ///
480    /// # Panics
481    ///
482    /// This function will panic if the key currently has its destructor
483    /// running, and it **may** panic if the destructor has previously been run
484    /// for this thread.
485    fn initialize_with<F, R>(&'static self, init: T, f: F) -> R
486    where
487        F: FnOnce(Option<T>, &T) -> R,
488    {
489        let mut init = Some(init);
490
491        let reference = unsafe {
492            match (self.inner)(Some(&mut init)).as_ref() {
493                Some(r) => r,
494                None => panic_access_error(AccessError),
495            }
496        };
497
498        f(init, reference)
499    }
500}
501
502impl<T: 'static> LocalKey<Cell<T>> {
503    /// Sets or initializes the contained value.
504    ///
505    /// Unlike the other methods, this will *not* run the lazy initializer of
506    /// the thread local. Instead, it will be directly initialized with the
507    /// given value if it wasn't initialized yet.
508    ///
509    /// # Panics
510    ///
511    /// Panics if the key currently has its destructor running,
512    /// and it **may** panic if the destructor has previously been run for this thread.
513    ///
514    /// # Examples
515    ///
516    /// ```
517    /// use std::cell::Cell;
518    ///
519    /// thread_local! {
520    ///     static X: Cell<i32> = panic!("!");
521    /// }
522    ///
523    /// // Calling X.get() here would result in a panic.
524    ///
525    /// X.set(123); // But X.set() is fine, as it skips the initializer above.
526    ///
527    /// assert_eq!(X.get(), 123);
528    /// ```
529    #[stable(feature = "local_key_cell_methods", since = "1.73.0")]
530    pub fn set(&'static self, value: T) {
531        self.initialize_with(Cell::new(value), |value, cell| {
532            if let Some(value) = value {
533                // The cell was already initialized, so `value` wasn't used to
534                // initialize it. So we overwrite the current value with the
535                // new one instead.
536                cell.set(value.into_inner());
537            }
538        });
539    }
540
541    /// Returns a copy of the contained value.
542    ///
543    /// This will lazily initialize the value if this thread has not referenced
544    /// this key yet.
545    ///
546    /// # Panics
547    ///
548    /// Panics if the key currently has its destructor running,
549    /// and it **may** panic if the destructor has previously been run for this thread.
550    ///
551    /// # Examples
552    ///
553    /// ```
554    /// use std::cell::Cell;
555    ///
556    /// thread_local! {
557    ///     static X: Cell<i32> = const { Cell::new(1) };
558    /// }
559    ///
560    /// assert_eq!(X.get(), 1);
561    /// ```
562    #[stable(feature = "local_key_cell_methods", since = "1.73.0")]
563    pub fn get(&'static self) -> T
564    where
565        T: Copy,
566    {
567        self.with(Cell::get)
568    }
569
570    /// Takes the contained value, leaving `Default::default()` in its place.
571    ///
572    /// This will lazily initialize the value if this thread has not referenced
573    /// this key yet.
574    ///
575    /// # Panics
576    ///
577    /// Panics if the key currently has its destructor running,
578    /// and it **may** panic if the destructor has previously been run for this thread.
579    ///
580    /// # Examples
581    ///
582    /// ```
583    /// use std::cell::Cell;
584    ///
585    /// thread_local! {
586    ///     static X: Cell<Option<i32>> = const { Cell::new(Some(1)) };
587    /// }
588    ///
589    /// assert_eq!(X.take(), Some(1));
590    /// assert_eq!(X.take(), None);
591    /// ```
592    #[stable(feature = "local_key_cell_methods", since = "1.73.0")]
593    pub fn take(&'static self) -> T
594    where
595        T: Default,
596    {
597        self.with(Cell::take)
598    }
599
600    /// Replaces the contained value, returning the old value.
601    ///
602    /// This will lazily initialize the value if this thread has not referenced
603    /// this key yet.
604    ///
605    /// # Panics
606    ///
607    /// Panics if the key currently has its destructor running,
608    /// and it **may** panic if the destructor has previously been run for this thread.
609    ///
610    /// # Examples
611    ///
612    /// ```
613    /// use std::cell::Cell;
614    ///
615    /// thread_local! {
616    ///     static X: Cell<i32> = const { Cell::new(1) };
617    /// }
618    ///
619    /// assert_eq!(X.replace(2), 1);
620    /// assert_eq!(X.replace(3), 2);
621    /// ```
622    #[stable(feature = "local_key_cell_methods", since = "1.73.0")]
623    #[rustc_confusables("swap")]
624    pub fn replace(&'static self, value: T) -> T {
625        self.with(|cell| cell.replace(value))
626    }
627
628    /// Updates the contained value using a function.
629    ///
630    /// This will lazily initialize the value if this thread has not referenced
631    /// this key yet.
632    ///
633    /// # Panics
634    ///
635    /// Panics if the key currently has its destructor running,
636    /// and it **may** panic if the destructor has previously been run for this thread.
637    ///
638    /// # Examples
639    ///
640    /// ```
641    /// use std::cell::Cell;
642    ///
643    /// thread_local! {
644    ///     static X: Cell<i32> = const { Cell::new(5) };
645    /// }
646    ///
647    /// X.update(|x| x + 1);
648    /// assert_eq!(X.get(), 6);
649    /// ```
650    #[stable(feature = "local_key_cell_update", since = "1.99.0")]
651    pub fn update(&'static self, f: impl FnOnce(T) -> T)
652    where
653        T: Copy,
654    {
655        self.with(|cell| cell.update(f))
656    }
657}
658
659impl<T: 'static> LocalKey<RefCell<T>> {
660    /// Acquires a reference to the contained value.
661    ///
662    /// This will lazily initialize the value if this thread has not referenced
663    /// this key yet.
664    ///
665    /// # Panics
666    ///
667    /// Panics if the value is currently mutably borrowed.
668    ///
669    /// Panics if the key currently has its destructor running,
670    /// and it **may** panic if the destructor has previously been run for this thread.
671    ///
672    /// # Examples
673    ///
674    /// ```
675    /// use std::cell::RefCell;
676    ///
677    /// thread_local! {
678    ///     static X: RefCell<Vec<i32>> = RefCell::new(Vec::new());
679    /// }
680    ///
681    /// X.with_borrow(|v| assert!(v.is_empty()));
682    /// ```
683    #[stable(feature = "local_key_cell_methods", since = "1.73.0")]
684    pub fn with_borrow<F, R>(&'static self, f: F) -> R
685    where
686        F: FnOnce(&T) -> R,
687    {
688        self.with(|cell| f(&cell.borrow()))
689    }
690
691    /// Acquires a mutable 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 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_mut(|v| v.push(1));
713    ///
714    /// X.with_borrow(|v| assert_eq!(*v, vec![1]));
715    /// ```
716    #[stable(feature = "local_key_cell_methods", since = "1.73.0")]
717    pub fn with_borrow_mut<F, R>(&'static self, f: F) -> R
718    where
719        F: FnOnce(&mut T) -> R,
720    {
721        self.with(|cell| f(&mut cell.borrow_mut()))
722    }
723
724    /// Sets or initializes the contained value.
725    ///
726    /// Unlike the other methods, this will *not* run the lazy initializer of
727    /// the thread local. Instead, it will be directly initialized with the
728    /// given value if it wasn't initialized yet.
729    ///
730    /// # Panics
731    ///
732    /// Panics if the value is currently borrowed.
733    ///
734    /// Panics if the key currently has its destructor running,
735    /// and it **may** panic if the destructor has previously been run for this thread.
736    ///
737    /// # Examples
738    ///
739    /// ```
740    /// use std::cell::RefCell;
741    ///
742    /// thread_local! {
743    ///     static X: RefCell<Vec<i32>> = panic!("!");
744    /// }
745    ///
746    /// // Calling X.with() here would result in a panic.
747    ///
748    /// X.set(vec![1, 2, 3]); // But X.set() is fine, as it skips the initializer above.
749    ///
750    /// X.with_borrow(|v| assert_eq!(*v, vec![1, 2, 3]));
751    /// ```
752    #[stable(feature = "local_key_cell_methods", since = "1.73.0")]
753    pub fn set(&'static self, value: T) {
754        self.initialize_with(RefCell::new(value), |value, cell| {
755            if let Some(value) = value {
756                // The cell was already initialized, so `value` wasn't used to
757                // initialize it. So we overwrite the current value with the
758                // new one instead.
759                *cell.borrow_mut() = value.into_inner();
760            }
761        });
762    }
763
764    /// Takes the contained value, leaving `Default::default()` in its place.
765    ///
766    /// This will lazily initialize the value if this thread has not referenced
767    /// this key yet.
768    ///
769    /// # Panics
770    ///
771    /// Panics if the value is currently borrowed.
772    ///
773    /// Panics if the key currently has its destructor running,
774    /// and it **may** panic if the destructor has previously been run for this thread.
775    ///
776    /// # Examples
777    ///
778    /// ```
779    /// use std::cell::RefCell;
780    ///
781    /// thread_local! {
782    ///     static X: RefCell<Vec<i32>> = RefCell::new(Vec::new());
783    /// }
784    ///
785    /// X.with_borrow_mut(|v| v.push(1));
786    ///
787    /// let a = X.take();
788    ///
789    /// assert_eq!(a, vec![1]);
790    ///
791    /// X.with_borrow(|v| assert!(v.is_empty()));
792    /// ```
793    #[stable(feature = "local_key_cell_methods", since = "1.73.0")]
794    pub fn take(&'static self) -> T
795    where
796        T: Default,
797    {
798        self.with(RefCell::take)
799    }
800
801    /// Replaces the contained value, returning the old value.
802    ///
803    /// # Panics
804    ///
805    /// Panics if the value is currently borrowed.
806    ///
807    /// Panics if the key currently has its destructor running,
808    /// and it **may** panic if the destructor has previously been run for this thread.
809    ///
810    /// # Examples
811    ///
812    /// ```
813    /// use std::cell::RefCell;
814    ///
815    /// thread_local! {
816    ///     static X: RefCell<Vec<i32>> = RefCell::new(Vec::new());
817    /// }
818    ///
819    /// let prev = X.replace(vec![1, 2, 3]);
820    /// assert!(prev.is_empty());
821    ///
822    /// X.with_borrow(|v| assert_eq!(*v, vec![1, 2, 3]));
823    /// ```
824    #[stable(feature = "local_key_cell_methods", since = "1.73.0")]
825    #[rustc_confusables("swap")]
826    pub fn replace(&'static self, value: T) -> T {
827        self.with(|cell| cell.replace(value))
828    }
829}