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