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 inner: fn(Option<&mut Option<T>>) -> *const T,
131}
132
133#[stable(feature = "std_debug", since = "1.16.0")]
134impl<T: 'static> fmt::Debug for LocalKey<T> {
135 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
136 f.debug_struct("LocalKey").finish_non_exhaustive()
137 }
138}
139
140#[doc(hidden)]
141#[allow_internal_unstable(thread_local_internals)]
142#[unstable(feature = "thread_local_internals", issue = "none")]
143#[rustc_macro_transparency = "semiopaque"]
144pub macro thread_local_process_attrs {
145
146 // Parse `cfg_attr` to figure out whether it's a `rustc_align_static`.
147 // Each `cfg_attr` can have zero or more attributes on the RHS, and can be nested.
148
149 // finished parsing the `cfg_attr`, it had no `rustc_align_static`
150 (
151 [] [$(#[$($prev_other_attrs:tt)*])*];
152 @processing_cfg_attr { pred: ($($predicate:tt)*), rhs: [] };
153 [$($prev_align_attrs_ret:tt)*] [$($prev_other_attrs_ret:tt)*];
154 $($rest:tt)*
155 ) => (
156 $crate::thread::local_impl::thread_local_process_attrs!(
157 [$($prev_align_attrs_ret)*] [$($prev_other_attrs_ret)* #[cfg_attr($($predicate)*, $($($prev_other_attrs)*),*)]];
158 $($rest)*
159 );
160 ),
161
162 // finished parsing the `cfg_attr`, it had nothing but `rustc_align_static`
163 (
164 [$(#[$($prev_align_attrs:tt)*])+] [];
165 @processing_cfg_attr { pred: ($($predicate:tt)*), rhs: [] };
166 [$($prev_align_attrs_ret:tt)*] [$($prev_other_attrs_ret:tt)*];
167 $($rest:tt)*
168 ) => (
169 $crate::thread::local_impl::thread_local_process_attrs!(
170 [$($prev_align_attrs_ret)* #[cfg_attr($($predicate)*, $($($prev_align_attrs)*),+)]] [$($prev_other_attrs_ret)*];
171 $($rest)*
172 );
173 ),
174
175 // finished parsing the `cfg_attr`, it had a mix of `rustc_align_static` and other attrs
176 (
177 [$(#[$($prev_align_attrs:tt)*])+] [$(#[$($prev_other_attrs:tt)*])+];
178 @processing_cfg_attr { pred: ($($predicate:tt)*), rhs: [] };
179 [$($prev_align_attrs_ret:tt)*] [$($prev_other_attrs_ret:tt)*];
180 $($rest:tt)*
181 ) => (
182 $crate::thread::local_impl::thread_local_process_attrs!(
183 [$($prev_align_attrs_ret)* #[cfg_attr($($predicate)*, $($($prev_align_attrs)*),+)]] [$($prev_other_attrs_ret)* #[cfg_attr($($predicate)*, $($($prev_other_attrs)*),+)]];
184 $($rest)*
185 );
186 ),
187
188 // it's a `rustc_align_static`
189 (
190 [$($prev_align_attrs:tt)*] [$($prev_other_attrs:tt)*];
191 @processing_cfg_attr { pred: ($($predicate:tt)*), rhs: [rustc_align_static($($align_static_args:tt)*) $(, $($attr_rhs:tt)*)?] };
192 $($rest:tt)*
193 ) => (
194 $crate::thread::local_impl::thread_local_process_attrs!(
195 [$($prev_align_attrs)* #[rustc_align_static($($align_static_args)*)]] [$($prev_other_attrs)*];
196 @processing_cfg_attr { pred: ($($predicate)*), rhs: [$($($attr_rhs)*)?] };
197 $($rest)*
198 );
199 ),
200
201 // it's a nested `cfg_attr(..., ...)`; recurse into RHS
202 (
203 [$($prev_align_attrs:tt)*] [$($prev_other_attrs:tt)*];
204 @processing_cfg_attr { pred: ($($predicate:tt)*), rhs: [cfg_attr($cfg_lhs:expr, $($cfg_rhs:tt)*) $(, $($attr_rhs:tt)*)?] };
205 $($rest:tt)*
206 ) => (
207 $crate::thread::local_impl::thread_local_process_attrs!(
208 [] [];
209 @processing_cfg_attr { pred: ($cfg_lhs), rhs: [$($cfg_rhs)*] };
210 [$($prev_align_attrs)*] [$($prev_other_attrs)*];
211 @processing_cfg_attr { pred: ($($predicate)*), rhs: [$($($attr_rhs)*)?] };
212 $($rest)*
213 );
214 ),
215
216 // it's some other attribute
217 (
218 [$($prev_align_attrs:tt)*] [$($prev_other_attrs:tt)*];
219 @processing_cfg_attr { pred: ($($predicate:tt)*), rhs: [$meta:meta $(, $($attr_rhs:tt)*)?] };
220 $($rest:tt)*
221 ) => (
222 $crate::thread::local_impl::thread_local_process_attrs!(
223 [$($prev_align_attrs)*] [$($prev_other_attrs)* #[$meta]];
224 @processing_cfg_attr { pred: ($($predicate)*), rhs: [$($($attr_rhs)*)?] };
225 $($rest)*
226 );
227 ),
228
229
230 // Separate attributes into `rustc_align_static` and everything else:
231
232 // `rustc_align_static` attribute
233 ([$($prev_align_attrs:tt)*] [$($prev_other_attrs:tt)*]; #[rustc_align_static $($attr_rest:tt)*] $($rest:tt)*) => (
234 $crate::thread::local_impl::thread_local_process_attrs!(
235 [$($prev_align_attrs)* #[rustc_align_static $($attr_rest)*]] [$($prev_other_attrs)*];
236 $($rest)*
237 );
238 ),
239
240 // `cfg_attr(..., ...)` attribute; parse it
241 ([$($prev_align_attrs:tt)*] [$($prev_other_attrs:tt)*]; #[cfg_attr($cfg_pred:expr, $($cfg_rhs:tt)*)] $($rest:tt)*) => (
242 $crate::thread::local_impl::thread_local_process_attrs!(
243 [] [];
244 @processing_cfg_attr { pred: ($cfg_pred), rhs: [$($cfg_rhs)*] };
245 [$($prev_align_attrs)*] [$($prev_other_attrs)*];
246 $($rest)*
247 );
248 ),
249
250 // doc comment not followed by any other attributes; process it all at once to avoid blowing recursion limit
251 ([$($prev_align_attrs:tt)*] [$($prev_other_attrs:tt)*]; $(#[doc $($doc_rhs:tt)*])+ $vis:vis static $($rest:tt)*) => (
252 $crate::thread::local_impl::thread_local_process_attrs!(
253 [$($prev_align_attrs)*] [$($prev_other_attrs)* $(#[doc $($doc_rhs)*])+];
254 $vis static $($rest)*
255 );
256 ),
257
258 // 8 lines of doc comment; process them all at once to avoid blowing recursion limit
259 ([$($prev_align_attrs:tt)*] [$($prev_other_attrs:tt)*];
260 #[doc $($doc_rhs_1:tt)*] #[doc $($doc_rhs_2:tt)*] #[doc $($doc_rhs_3:tt)*] #[doc $($doc_rhs_4:tt)*]
261 #[doc $($doc_rhs_5:tt)*] #[doc $($doc_rhs_6:tt)*] #[doc $($doc_rhs_7:tt)*] #[doc $($doc_rhs_8:tt)*]
262 $($rest:tt)*) => (
263 $crate::thread::local_impl::thread_local_process_attrs!(
264 [$($prev_align_attrs)*] [$($prev_other_attrs)*
265 #[doc $($doc_rhs_1)*] #[doc $($doc_rhs_2)*] #[doc $($doc_rhs_3)*] #[doc $($doc_rhs_4)*]
266 #[doc $($doc_rhs_5)*] #[doc $($doc_rhs_6)*] #[doc $($doc_rhs_7)*] #[doc $($doc_rhs_8)*]];
267 $($rest)*
268 );
269 ),
270
271 // other attribute
272 ([$($prev_align_attrs:tt)*] [$($prev_other_attrs:tt)*]; #[$($attr:tt)*] $($rest:tt)*) => (
273 $crate::thread::local_impl::thread_local_process_attrs!(
274 [$($prev_align_attrs)*] [$($prev_other_attrs)* #[$($attr)*]];
275 $($rest)*
276 );
277 ),
278
279
280 // Delegate to `thread_local_inner` once attributes are fully categorized:
281
282 // process `const` declaration and recurse
283 ([$($align_attrs:tt)*] [$($other_attrs:tt)*]; $vis:vis static $name:ident: $t:ty = const $init:block $(; $($($rest:tt)+)?)?) => (
284 $($other_attrs)* $vis const $name: $crate::thread::LocalKey<$t> =
285 $crate::thread::local_impl::thread_local_inner!(@key $t, $($align_attrs)*, const $init);
286
287 $($($crate::thread::local_impl::thread_local_process_attrs!([] []; $($rest)+);)?)?
288 ),
289
290 // process non-`const` declaration and recurse
291 ([$($align_attrs:tt)*] [$($other_attrs:tt)*]; $vis:vis static $name:ident: $t:ty = $init:expr $(; $($($rest:tt)+)?)?) => (
292 $($other_attrs)* $vis const $name: $crate::thread::LocalKey<$t> =
293 $crate::thread::local_impl::thread_local_inner!(@key $t, $($align_attrs)*, $init);
294
295 $($($crate::thread::local_impl::thread_local_process_attrs!([] []; $($rest)+);)?)?
296 ),
297}
298
299/// Declare a new thread local storage key of type [`std::thread::LocalKey`].
300///
301/// # Syntax
302///
303/// The macro wraps any number of static declarations and makes them thread local.
304/// Publicity and attributes for each static are allowed. Example:
305///
306/// ```
307/// use std::cell::{Cell, RefCell};
308///
309/// thread_local! {
310/// pub static FOO: Cell<u32> = const { Cell::new(1) };
311///
312/// static BAR: RefCell<Vec<f32>> = RefCell::new(vec![1.0, 2.0]);
313/// }
314///
315/// assert_eq!(FOO.get(), 1);
316/// BAR.with_borrow(|v| assert_eq!(v[1], 2.0));
317/// ```
318///
319/// Note that only shared references (`&T`) to the inner data may be obtained, so a
320/// type such as [`Cell`] or [`RefCell`] is typically used to allow mutating access.
321///
322/// This macro supports a special `const {}` syntax that can be used
323/// when the initialization expression can be evaluated as a constant.
324/// This can enable a more efficient thread local implementation that
325/// can avoid lazy initialization. For types that do not
326/// [need to be dropped][crate::mem::needs_drop], this can enable an
327/// even more efficient implementation that does not need to
328/// track any additional state.
329///
330/// ```
331/// use std::cell::RefCell;
332///
333/// thread_local! {
334/// pub static FOO: RefCell<Vec<u32>> = const { RefCell::new(Vec::new()) };
335/// }
336///
337/// FOO.with_borrow(|v| assert_eq!(v.len(), 0));
338/// ```
339///
340/// See [`LocalKey` documentation][`std::thread::LocalKey`] for more
341/// information.
342///
343/// [`std::thread::LocalKey`]: crate::thread::LocalKey
344#[macro_export]
345#[stable(feature = "rust1", since = "1.0.0")]
346#[cfg_attr(not(test), rustc_diagnostic_item = "thread_local_macro")]
347#[allow_internal_unstable(thread_local_internals)]
348#[rustc_diagnostic_opaque]
349macro_rules! thread_local {
350 () => {};
351
352 ($($tt:tt)+) => {
353 $crate::thread::local_impl::thread_local_process_attrs!([] []; $($tt)+);
354 };
355}
356
357/// An error returned by [`LocalKey::try_with`](struct.LocalKey.html#method.try_with).
358#[stable(feature = "thread_local_try_with", since = "1.26.0")]
359#[non_exhaustive]
360#[derive(Clone, Copy, Eq, PartialEq)]
361pub struct AccessError;
362
363#[stable(feature = "thread_local_try_with", since = "1.26.0")]
364impl fmt::Debug for AccessError {
365 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
366 f.debug_struct("AccessError").finish()
367 }
368}
369
370#[stable(feature = "thread_local_try_with", since = "1.26.0")]
371impl fmt::Display for AccessError {
372 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
373 fmt::Display::fmt("already destroyed", f)
374 }
375}
376
377#[stable(feature = "thread_local_try_with", since = "1.26.0")]
378impl Error for AccessError {}
379
380// This ensures the panicking code is outlined from `with` for `LocalKey`.
381#[cfg_attr(not(panic = "immediate-abort"), inline(never))]
382#[track_caller]
383#[cold]
384fn panic_access_error(err: AccessError) -> ! {
385 panic!("cannot access a Thread Local Storage value during or after destruction: {err:?}")
386}
387
388impl<T: 'static> LocalKey<T> {
389 #[doc(hidden)]
390 #[unstable(
391 feature = "thread_local_internals",
392 reason = "recently added to create a key",
393 issue = "none"
394 )]
395 pub const unsafe fn new(inner: fn(Option<&mut Option<T>>) -> *const T) -> LocalKey<T> {
396 LocalKey { inner }
397 }
398
399 /// Acquires a reference to the value in this TLS key.
400 ///
401 /// This will lazily initialize the value if this thread has not referenced
402 /// this key yet.
403 ///
404 /// # Panics
405 ///
406 /// This function will `panic!()` if the key currently has its
407 /// destructor running, and it **may** panic if the destructor has
408 /// previously been run for this thread.
409 ///
410 /// # Examples
411 ///
412 /// ```
413 /// thread_local! {
414 /// pub static STATIC: String = String::from("I am");
415 /// }
416 ///
417 /// assert_eq!(
418 /// STATIC.with(|original_value| format!("{original_value} initialized")),
419 /// "I am initialized",
420 /// );
421 /// ```
422 #[stable(feature = "rust1", since = "1.0.0")]
423 pub fn with<F, R>(&'static self, f: F) -> R
424 where
425 F: FnOnce(&T) -> R,
426 {
427 match self.try_with(f) {
428 Ok(r) => r,
429 Err(err) => panic_access_error(err),
430 }
431 }
432
433 /// Acquires a reference to the value in this TLS key.
434 ///
435 /// This will lazily initialize the value if this thread has not referenced
436 /// this key yet. If the key has been destroyed (which may happen if this is called
437 /// in a destructor), this function may return an [`AccessError`].
438 ///
439 /// # Panics
440 ///
441 /// This function will still `panic!()` if the key is uninitialized and the
442 /// key's initializer panics.
443 ///
444 /// # Examples
445 ///
446 /// ```
447 /// thread_local! {
448 /// pub static STATIC: String = String::from("I am");
449 /// }
450 ///
451 /// assert_eq!(
452 /// STATIC.try_with(|original_value| format!("{original_value} initialized")),
453 /// Ok(String::from("I am initialized")),
454 /// );
455 /// ```
456 #[stable(feature = "thread_local_try_with", since = "1.26.0")]
457 #[inline]
458 pub fn try_with<F, R>(&'static self, f: F) -> Result<R, AccessError>
459 where
460 F: FnOnce(&T) -> R,
461 {
462 let thread_local = unsafe { (self.inner)(None).as_ref().ok_or(AccessError)? };
463 Ok(f(thread_local))
464 }
465
466 /// Acquires a reference to the value in this TLS key, initializing it with
467 /// `init` if it wasn't already initialized on this thread.
468 ///
469 /// If `init` was used to initialize the thread local variable, `None` is
470 /// passed as the first argument to `f`. If it was already initialized,
471 /// `Some(init)` is passed to `f`.
472 ///
473 /// # Panics
474 ///
475 /// This function will panic if the key currently has its destructor
476 /// running, and it **may** panic if the destructor has previously been run
477 /// for this thread.
478 fn initialize_with<F, R>(&'static self, init: T, f: F) -> R
479 where
480 F: FnOnce(Option<T>, &T) -> R,
481 {
482 let mut init = Some(init);
483
484 let reference = unsafe {
485 match (self.inner)(Some(&mut init)).as_ref() {
486 Some(r) => r,
487 None => panic_access_error(AccessError),
488 }
489 };
490
491 f(init, reference)
492 }
493}
494
495impl<T: 'static> LocalKey<Cell<T>> {
496 /// Sets or initializes the contained value.
497 ///
498 /// Unlike the other methods, this will *not* run the lazy initializer of
499 /// the thread local. Instead, it will be directly initialized with the
500 /// given value if it wasn't initialized yet.
501 ///
502 /// # Panics
503 ///
504 /// Panics if the key currently has its destructor running,
505 /// and it **may** panic if the destructor has previously been run for this thread.
506 ///
507 /// # Examples
508 ///
509 /// ```
510 /// use std::cell::Cell;
511 ///
512 /// thread_local! {
513 /// static X: Cell<i32> = panic!("!");
514 /// }
515 ///
516 /// // Calling X.get() here would result in a panic.
517 ///
518 /// X.set(123); // But X.set() is fine, as it skips the initializer above.
519 ///
520 /// assert_eq!(X.get(), 123);
521 /// ```
522 #[stable(feature = "local_key_cell_methods", since = "1.73.0")]
523 pub fn set(&'static self, value: T) {
524 self.initialize_with(Cell::new(value), |value, cell| {
525 if let Some(value) = value {
526 // The cell was already initialized, so `value` wasn't used to
527 // initialize it. So we overwrite the current value with the
528 // new one instead.
529 cell.set(value.into_inner());
530 }
531 });
532 }
533
534 /// Returns a copy of the contained value.
535 ///
536 /// This will lazily initialize the value if this thread has not referenced
537 /// this key yet.
538 ///
539 /// # Panics
540 ///
541 /// Panics if the key currently has its destructor running,
542 /// and it **may** panic if the destructor has previously been run for this thread.
543 ///
544 /// # Examples
545 ///
546 /// ```
547 /// use std::cell::Cell;
548 ///
549 /// thread_local! {
550 /// static X: Cell<i32> = const { Cell::new(1) };
551 /// }
552 ///
553 /// assert_eq!(X.get(), 1);
554 /// ```
555 #[stable(feature = "local_key_cell_methods", since = "1.73.0")]
556 pub fn get(&'static self) -> T
557 where
558 T: Copy,
559 {
560 self.with(Cell::get)
561 }
562
563 /// Takes the contained value, leaving `Default::default()` in its place.
564 ///
565 /// This will lazily initialize the value if this thread has not referenced
566 /// this key yet.
567 ///
568 /// # Panics
569 ///
570 /// Panics if the key currently has its destructor running,
571 /// and it **may** panic if the destructor has previously been run for this thread.
572 ///
573 /// # Examples
574 ///
575 /// ```
576 /// use std::cell::Cell;
577 ///
578 /// thread_local! {
579 /// static X: Cell<Option<i32>> = const { Cell::new(Some(1)) };
580 /// }
581 ///
582 /// assert_eq!(X.take(), Some(1));
583 /// assert_eq!(X.take(), None);
584 /// ```
585 #[stable(feature = "local_key_cell_methods", since = "1.73.0")]
586 pub fn take(&'static self) -> T
587 where
588 T: Default,
589 {
590 self.with(Cell::take)
591 }
592
593 /// Replaces the contained value, returning the old value.
594 ///
595 /// This will lazily initialize the value if this thread has not referenced
596 /// this key yet.
597 ///
598 /// # Panics
599 ///
600 /// Panics if the key currently has its destructor running,
601 /// and it **may** panic if the destructor has previously been run for this thread.
602 ///
603 /// # Examples
604 ///
605 /// ```
606 /// use std::cell::Cell;
607 ///
608 /// thread_local! {
609 /// static X: Cell<i32> = const { Cell::new(1) };
610 /// }
611 ///
612 /// assert_eq!(X.replace(2), 1);
613 /// assert_eq!(X.replace(3), 2);
614 /// ```
615 #[stable(feature = "local_key_cell_methods", since = "1.73.0")]
616 #[rustc_confusables("swap")]
617 pub fn replace(&'static self, value: T) -> T {
618 self.with(|cell| cell.replace(value))
619 }
620
621 /// Updates the contained value using a function.
622 ///
623 /// This will lazily initialize the value if this thread has not referenced
624 /// this key yet.
625 ///
626 /// # Panics
627 ///
628 /// Panics if the key currently has its destructor running,
629 /// and it **may** panic if the destructor has previously been run for this thread.
630 ///
631 /// # Examples
632 ///
633 /// ```
634 /// use std::cell::Cell;
635 ///
636 /// thread_local! {
637 /// static X: Cell<i32> = const { Cell::new(5) };
638 /// }
639 ///
640 /// X.update(|x| x + 1);
641 /// assert_eq!(X.get(), 6);
642 /// ```
643 #[stable(feature = "local_key_cell_update", since = "1.99.0")]
644 pub fn update(&'static self, f: impl FnOnce(T) -> T)
645 where
646 T: Copy,
647 {
648 self.with(|cell| cell.update(f))
649 }
650}
651
652impl<T: 'static> LocalKey<RefCell<T>> {
653 /// Acquires a reference to the contained value.
654 ///
655 /// This will lazily initialize the value if this thread has not referenced
656 /// this key yet.
657 ///
658 /// # Panics
659 ///
660 /// Panics if the value is currently mutably borrowed.
661 ///
662 /// Panics if the key currently has its destructor running,
663 /// and it **may** panic if the destructor has previously been run for this thread.
664 ///
665 /// # Examples
666 ///
667 /// ```
668 /// use std::cell::RefCell;
669 ///
670 /// thread_local! {
671 /// static X: RefCell<Vec<i32>> = RefCell::new(Vec::new());
672 /// }
673 ///
674 /// X.with_borrow(|v| assert!(v.is_empty()));
675 /// ```
676 #[stable(feature = "local_key_cell_methods", since = "1.73.0")]
677 pub fn with_borrow<F, R>(&'static self, f: F) -> R
678 where
679 F: FnOnce(&T) -> R,
680 {
681 self.with(|cell| f(&cell.borrow()))
682 }
683
684 /// Acquires a mutable reference to the contained value.
685 ///
686 /// This will lazily initialize the value if this thread has not referenced
687 /// this key yet.
688 ///
689 /// # Panics
690 ///
691 /// Panics if the value is currently borrowed.
692 ///
693 /// Panics if the key currently has its destructor running,
694 /// and it **may** panic if the destructor has previously been run for this thread.
695 ///
696 /// # Examples
697 ///
698 /// ```
699 /// use std::cell::RefCell;
700 ///
701 /// thread_local! {
702 /// static X: RefCell<Vec<i32>> = RefCell::new(Vec::new());
703 /// }
704 ///
705 /// X.with_borrow_mut(|v| v.push(1));
706 ///
707 /// X.with_borrow(|v| assert_eq!(*v, vec![1]));
708 /// ```
709 #[stable(feature = "local_key_cell_methods", since = "1.73.0")]
710 pub fn with_borrow_mut<F, R>(&'static self, f: F) -> R
711 where
712 F: FnOnce(&mut T) -> R,
713 {
714 self.with(|cell| f(&mut cell.borrow_mut()))
715 }
716
717 /// Sets or initializes the contained value.
718 ///
719 /// Unlike the other methods, this will *not* run the lazy initializer of
720 /// the thread local. Instead, it will be directly initialized with the
721 /// given value if it wasn't initialized yet.
722 ///
723 /// # Panics
724 ///
725 /// Panics if the value is currently borrowed.
726 ///
727 /// Panics if the key currently has its destructor running,
728 /// and it **may** panic if the destructor has previously been run for this thread.
729 ///
730 /// # Examples
731 ///
732 /// ```
733 /// use std::cell::RefCell;
734 ///
735 /// thread_local! {
736 /// static X: RefCell<Vec<i32>> = panic!("!");
737 /// }
738 ///
739 /// // Calling X.with() here would result in a panic.
740 ///
741 /// X.set(vec![1, 2, 3]); // But X.set() is fine, as it skips the initializer above.
742 ///
743 /// X.with_borrow(|v| assert_eq!(*v, vec![1, 2, 3]));
744 /// ```
745 #[stable(feature = "local_key_cell_methods", since = "1.73.0")]
746 pub fn set(&'static self, value: T) {
747 self.initialize_with(RefCell::new(value), |value, cell| {
748 if let Some(value) = value {
749 // The cell was already initialized, so `value` wasn't used to
750 // initialize it. So we overwrite the current value with the
751 // new one instead.
752 *cell.borrow_mut() = value.into_inner();
753 }
754 });
755 }
756
757 /// Takes the contained value, leaving `Default::default()` in its place.
758 ///
759 /// This will lazily initialize the value if this thread has not referenced
760 /// this key yet.
761 ///
762 /// # Panics
763 ///
764 /// Panics if the value is currently borrowed.
765 ///
766 /// Panics if the key currently has its destructor running,
767 /// and it **may** panic if the destructor has previously been run for this thread.
768 ///
769 /// # Examples
770 ///
771 /// ```
772 /// use std::cell::RefCell;
773 ///
774 /// thread_local! {
775 /// static X: RefCell<Vec<i32>> = RefCell::new(Vec::new());
776 /// }
777 ///
778 /// X.with_borrow_mut(|v| v.push(1));
779 ///
780 /// let a = X.take();
781 ///
782 /// assert_eq!(a, vec![1]);
783 ///
784 /// X.with_borrow(|v| assert!(v.is_empty()));
785 /// ```
786 #[stable(feature = "local_key_cell_methods", since = "1.73.0")]
787 pub fn take(&'static self) -> T
788 where
789 T: Default,
790 {
791 self.with(RefCell::take)
792 }
793
794 /// Replaces the contained value, returning the old value.
795 ///
796 /// # Panics
797 ///
798 /// Panics if the value is currently borrowed.
799 ///
800 /// Panics if the key currently has its destructor running,
801 /// and it **may** panic if the destructor has previously been run for this thread.
802 ///
803 /// # Examples
804 ///
805 /// ```
806 /// use std::cell::RefCell;
807 ///
808 /// thread_local! {
809 /// static X: RefCell<Vec<i32>> = RefCell::new(Vec::new());
810 /// }
811 ///
812 /// let prev = X.replace(vec![1, 2, 3]);
813 /// assert!(prev.is_empty());
814 ///
815 /// X.with_borrow(|v| assert_eq!(*v, vec![1, 2, 3]));
816 /// ```
817 #[stable(feature = "local_key_cell_methods", since = "1.73.0")]
818 #[rustc_confusables("swap")]
819 pub fn replace(&'static self, value: T) -> T {
820 self.with(|cell| cell.replace(value))
821 }
822}