2014-11-14 14:20:57 -08:00
|
|
|
//! Thread local storage
|
2015-03-20 00:46:13 -07:00
|
|
|
|
2019-12-21 13:16:18 +02:00
|
|
|
#![unstable(feature = "thread_local_internals", issue = "none")]
|
2014-11-14 14:20:57 -08:00
|
|
|
|
2020-08-27 13:45:01 +00:00
|
|
|
#[cfg(all(test, not(target_os = "emscripten")))]
|
|
|
|
|
mod tests;
|
|
|
|
|
|
|
|
|
|
#[cfg(test)]
|
|
|
|
|
mod dynamic_tests;
|
|
|
|
|
|
2021-10-19 14:37:27 +02:00
|
|
|
use crate::cell::{Cell, RefCell};
|
2019-06-03 18:20:38 +02:00
|
|
|
use crate::error::Error;
|
2019-02-11 04:23:21 +09:00
|
|
|
use crate::fmt;
|
2014-11-14 14:20:57 -08:00
|
|
|
|
|
|
|
|
/// A thread local storage key which owns its contents.
|
|
|
|
|
///
|
|
|
|
|
/// This key uses the fastest possible implementation available to it for the
|
2017-05-14 20:06:54 +02:00
|
|
|
/// target platform. It is instantiated with the [`thread_local!`] macro and the
|
2024-01-02 17:24:59 -06:00
|
|
|
/// primary method is the [`with`] method, though there are helpers to make
|
|
|
|
|
/// working with [`Cell`] types easier.
|
2014-11-14 14:20:57 -08:00
|
|
|
///
|
2023-04-07 14:54:50 +02:00
|
|
|
/// The [`with`] method yields a reference to the contained value which cannot
|
|
|
|
|
/// outlive the current thread or escape the given closure.
|
2014-11-14 14:20:57 -08:00
|
|
|
///
|
2022-05-01 00:02:34 +03:00
|
|
|
/// [`thread_local!`]: crate::thread_local
|
|
|
|
|
///
|
2014-11-14 14:20:57 -08:00
|
|
|
/// # Initialization and Destruction
|
|
|
|
|
///
|
2024-01-02 17:24:59 -06:00
|
|
|
/// Initialization is dynamically performed on the first call to a setter (e.g.
|
|
|
|
|
/// [`with`]) within a thread, and values that implement [`Drop`] get
|
|
|
|
|
/// destructed when a thread exits. Some caveats apply, which are explained below.
|
2014-11-14 14:20:57 -08:00
|
|
|
///
|
2023-09-26 12:54:01 +02:00
|
|
|
/// A `LocalKey`'s initializer cannot recursively depend on itself. Using a
|
|
|
|
|
/// `LocalKey` in this way may cause panics, aborts or infinite recursion on
|
|
|
|
|
/// the first call to `with`.
|
2017-09-07 12:57:08 -07:00
|
|
|
///
|
2024-01-02 17:24:59 -06:00
|
|
|
/// # Single-thread Synchronization
|
|
|
|
|
///
|
|
|
|
|
/// Though there is no potential race with other threads, it is still possible to
|
|
|
|
|
/// obtain multiple references to the thread-local data in different places on
|
|
|
|
|
/// the call stack. For this reason, only shared (`&T`) references may be obtained.
|
|
|
|
|
///
|
|
|
|
|
/// To allow obtaining an exclusive mutable reference (`&mut T`), typically a
|
|
|
|
|
/// [`Cell`] or [`RefCell`] is used (see the [`std::cell`] for more information
|
|
|
|
|
/// on how exactly this works). To make this easier there are specialized
|
|
|
|
|
/// implementations for [`LocalKey<Cell<T>>`] and [`LocalKey<RefCell<T>>`].
|
|
|
|
|
///
|
|
|
|
|
/// [`std::cell`]: `crate::cell`
|
|
|
|
|
/// [`LocalKey<Cell<T>>`]: struct.LocalKey.html#impl-LocalKey<Cell<T>>
|
|
|
|
|
/// [`LocalKey<RefCell<T>>`]: struct.LocalKey.html#impl-LocalKey<RefCell<T>>
|
|
|
|
|
///
|
|
|
|
|
///
|
2015-03-11 21:11:40 -04:00
|
|
|
/// # Examples
|
2014-11-14 14:20:57 -08:00
|
|
|
///
|
|
|
|
|
/// ```
|
2024-04-08 17:43:24 -04:00
|
|
|
/// use std::cell::Cell;
|
2015-02-17 15:10:25 -08:00
|
|
|
/// use std::thread;
|
2014-11-14 14:20:57 -08:00
|
|
|
///
|
2024-04-08 17:43:24 -04:00
|
|
|
/// thread_local!(static FOO: Cell<u32> = Cell::new(1));
|
2014-11-14 14:20:57 -08:00
|
|
|
///
|
2024-04-08 17:43:24 -04:00
|
|
|
/// assert_eq!(FOO.get(), 1);
|
|
|
|
|
/// FOO.set(2);
|
2014-11-14 14:20:57 -08:00
|
|
|
///
|
|
|
|
|
/// // each thread starts out with the initial value of 1
|
2024-06-18 23:25:08 +08:00
|
|
|
/// let t = thread::spawn(move || {
|
2024-04-08 17:43:24 -04:00
|
|
|
/// assert_eq!(FOO.get(), 1);
|
|
|
|
|
/// FOO.set(3);
|
2015-01-05 21:59:45 -08:00
|
|
|
/// });
|
2014-11-14 14:20:57 -08:00
|
|
|
///
|
2019-03-03 15:21:52 +01:00
|
|
|
/// // wait for the thread to complete and bail out on panic
|
|
|
|
|
/// t.join().unwrap();
|
|
|
|
|
///
|
2014-11-14 14:20:57 -08:00
|
|
|
/// // we retain our original value of 2 despite the child thread
|
2024-04-08 17:43:24 -04:00
|
|
|
/// assert_eq!(FOO.get(), 2);
|
2014-11-14 14:20:57 -08:00
|
|
|
/// ```
|
2016-01-29 13:46:47 -08:00
|
|
|
///
|
|
|
|
|
/// # Platform-specific behavior
|
|
|
|
|
///
|
|
|
|
|
/// Note that a "best effort" is made to ensure that destructors for types
|
2016-04-25 21:01:19 +01:00
|
|
|
/// stored in thread local storage are run, but not all platforms can guarantee
|
2016-01-29 13:46:47 -08:00
|
|
|
/// that destructors will be run for all types in thread local storage. For
|
|
|
|
|
/// example, there are a number of known caveats where destructors are not run:
|
|
|
|
|
///
|
|
|
|
|
/// 1. On Unix systems when pthread-based TLS is being used, destructors will
|
|
|
|
|
/// not be run for TLS values on the main thread when it exits. Note that the
|
|
|
|
|
/// application will exit immediately after the main thread exits as well.
|
|
|
|
|
/// 2. On all platforms it's possible for TLS to re-initialize other TLS slots
|
|
|
|
|
/// during destruction. Some platforms ensure that this cannot happen
|
|
|
|
|
/// infinitely by preventing re-initialization of any slot that has been
|
|
|
|
|
/// destroyed, but not all platforms have this guard. Those platforms that do
|
|
|
|
|
/// not guard typically have a synthetic limit after which point no more
|
|
|
|
|
/// destructors are run.
|
2021-12-02 13:52:35 +00:00
|
|
|
/// 3. When the process exits on Windows systems, TLS destructors may only be
|
|
|
|
|
/// run on the thread that causes the process to exit. This is because the
|
|
|
|
|
/// other threads may be forcibly terminated.
|
2017-05-14 20:06:54 +02:00
|
|
|
///
|
2021-12-02 13:52:35 +00:00
|
|
|
/// ## Synchronization in thread-local destructors
|
|
|
|
|
///
|
|
|
|
|
/// On Windows, synchronization operations (such as [`JoinHandle::join`]) in
|
|
|
|
|
/// thread local destructors are prone to deadlocks and so should be avoided.
|
|
|
|
|
/// This is because the [loader lock] is held while a destructor is run. The
|
|
|
|
|
/// lock is acquired whenever a thread starts or exits or when a DLL is loaded
|
|
|
|
|
/// or unloaded. Therefore these events are blocked for as long as a thread
|
|
|
|
|
/// local destructor is running.
|
|
|
|
|
///
|
|
|
|
|
/// [loader lock]: https://docs.microsoft.com/en-us/windows/win32/dlls/dynamic-link-library-best-practices
|
|
|
|
|
/// [`JoinHandle::join`]: crate::thread::JoinHandle::join
|
2020-08-20 22:03:00 +02:00
|
|
|
/// [`with`]: LocalKey::with
|
2022-09-27 13:06:31 +02:00
|
|
|
#[cfg_attr(not(test), rustc_diagnostic_item = "LocalKey")]
|
2015-01-23 21:48:20 -08:00
|
|
|
#[stable(feature = "rust1", since = "1.0.0")]
|
2015-12-11 12:42:29 -08:00
|
|
|
pub struct LocalKey<T: 'static> {
|
|
|
|
|
// This outer `LocalKey<T>` type is what's going to be stored in statics,
|
|
|
|
|
// but actual data inside will sometimes be tagged with #[thread_local].
|
|
|
|
|
// It's not valid for a true static to reference a #[thread_local] static,
|
|
|
|
|
// so we get around that by exposing an accessor through a layer of function
|
|
|
|
|
// indirection (this thunk).
|
|
|
|
|
//
|
|
|
|
|
// Note that the thunk is itself unsafe because the returned lifetime of the
|
|
|
|
|
// slot where data lives, `'static`, is not actually valid. The lifetime
|
2017-08-08 18:22:51 +03:00
|
|
|
// here is actually slightly shorter than the currently running thread!
|
2014-11-14 14:20:57 -08:00
|
|
|
//
|
2015-12-11 12:42:29 -08:00
|
|
|
// Although this is an extra layer of indirection, it should in theory be
|
|
|
|
|
// trivially devirtualizable by LLVM because the value of `inner` never
|
|
|
|
|
// changes and the constant should be readonly within a crate. This mainly
|
|
|
|
|
// only runs into problems when TLS statics are exported across crates.
|
2024-05-25 00:19:47 +02:00
|
|
|
inner: fn(Option<&mut Option<T>>) -> *const T,
|
2014-11-14 09:18:10 -08:00
|
|
|
}
|
2014-11-14 14:20:57 -08:00
|
|
|
|
2017-01-29 13:31:47 +00:00
|
|
|
#[stable(feature = "std_debug", since = "1.16.0")]
|
2016-11-25 13:21:49 -05:00
|
|
|
impl<T: 'static> fmt::Debug for LocalKey<T> {
|
2019-03-01 09:34:11 +01:00
|
|
|
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
2021-04-05 13:31:11 +02:00
|
|
|
f.debug_struct("LocalKey").finish_non_exhaustive()
|
2016-11-25 13:21:49 -05:00
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2017-05-14 20:06:54 +02:00
|
|
|
/// Declare a new thread local storage key of type [`std::thread::LocalKey`].
|
2015-05-27 11:18:36 +03:00
|
|
|
///
|
2016-06-04 15:19:22 -04:00
|
|
|
/// # Syntax
|
|
|
|
|
///
|
|
|
|
|
/// The macro wraps any number of static declarations and makes them thread local.
|
2017-03-31 23:06:34 -04:00
|
|
|
/// Publicity and attributes for each static are allowed. Example:
|
2016-06-04 15:19:22 -04:00
|
|
|
///
|
|
|
|
|
/// ```
|
2024-04-08 17:43:24 -04:00
|
|
|
/// use std::cell::{Cell, RefCell};
|
|
|
|
|
///
|
2016-06-04 15:19:22 -04:00
|
|
|
/// thread_local! {
|
2024-04-08 17:43:24 -04:00
|
|
|
/// pub static FOO: Cell<u32> = Cell::new(1);
|
2016-06-04 15:19:22 -04:00
|
|
|
///
|
2024-04-08 17:43:24 -04:00
|
|
|
/// static BAR: RefCell<Vec<f32>> = RefCell::new(vec![1.0, 2.0]);
|
2016-06-04 15:19:22 -04:00
|
|
|
/// }
|
2023-04-20 19:48:08 +02:00
|
|
|
///
|
2024-04-08 17:43:24 -04:00
|
|
|
/// assert_eq!(FOO.get(), 1);
|
|
|
|
|
/// BAR.with_borrow(|v| assert_eq!(v[1], 2.0));
|
2023-04-20 19:48:08 +02:00
|
|
|
/// ```
|
|
|
|
|
///
|
2024-01-02 17:24:59 -06:00
|
|
|
/// Note that only shared references (`&T`) to the inner data may be obtained, so a
|
|
|
|
|
/// type such as [`Cell`] or [`RefCell`] is typically used to allow mutating access.
|
|
|
|
|
///
|
2023-04-20 19:48:08 +02:00
|
|
|
/// This macro supports a special `const {}` syntax that can be used
|
|
|
|
|
/// when the initialization expression can be evaluated as a constant.
|
|
|
|
|
/// This can enable a more efficient thread local implementation that
|
|
|
|
|
/// can avoid lazy initialization. For types that do not
|
|
|
|
|
/// [need to be dropped][crate::mem::needs_drop], this can enable an
|
|
|
|
|
/// even more efficient implementation that does not need to
|
|
|
|
|
/// track any additional state.
|
|
|
|
|
///
|
|
|
|
|
/// ```
|
2024-04-08 17:43:24 -04:00
|
|
|
/// use std::cell::RefCell;
|
|
|
|
|
///
|
2023-04-20 19:48:08 +02:00
|
|
|
/// thread_local! {
|
2024-04-08 17:43:24 -04:00
|
|
|
/// pub static FOO: RefCell<Vec<u32>> = const { RefCell::new(Vec::new()) };
|
2023-04-20 19:48:08 +02:00
|
|
|
/// }
|
|
|
|
|
///
|
2024-04-08 17:43:24 -04:00
|
|
|
/// FOO.with_borrow(|v| assert_eq!(v.len(), 0));
|
2016-06-04 15:19:22 -04:00
|
|
|
/// ```
|
|
|
|
|
///
|
2020-08-20 22:03:00 +02:00
|
|
|
/// See [`LocalKey` documentation][`std::thread::LocalKey`] for more
|
2015-05-27 23:24:27 -07:00
|
|
|
/// information.
|
2017-05-14 20:06:54 +02:00
|
|
|
///
|
2020-08-20 22:03:00 +02:00
|
|
|
/// [`std::thread::LocalKey`]: crate::thread::LocalKey
|
2014-11-14 14:20:57 -08:00
|
|
|
#[macro_export]
|
2015-05-27 11:18:36 +03:00
|
|
|
#[stable(feature = "rust1", since = "1.0.0")]
|
2022-01-06 14:50:46 +00:00
|
|
|
#[cfg_attr(not(test), rustc_diagnostic_item = "thread_local_macro")]
|
2019-02-27 16:58:12 -07:00
|
|
|
#[allow_internal_unstable(thread_local_internals)]
|
2015-05-27 23:24:27 -07:00
|
|
|
macro_rules! thread_local {
|
2017-03-31 23:06:34 -04:00
|
|
|
// empty (base case for the recursion)
|
2016-06-04 15:19:22 -04:00
|
|
|
() => {};
|
|
|
|
|
|
2023-10-03 14:44:41 -04:00
|
|
|
($(#[$attr:meta])* $vis:vis static $name:ident: $t:ty = const $init:block; $($rest:tt)*) => (
|
2023-04-26 21:02:29 +02:00
|
|
|
$crate::thread::local_impl::thread_local_inner!($(#[$attr])* $vis $name, $t, const $init);
|
2021-03-23 11:04:29 -07:00
|
|
|
$crate::thread_local!($($rest)*);
|
|
|
|
|
);
|
|
|
|
|
|
2023-10-03 14:44:41 -04:00
|
|
|
($(#[$attr:meta])* $vis:vis static $name:ident: $t:ty = const $init:block) => (
|
2023-04-26 21:02:29 +02:00
|
|
|
$crate::thread::local_impl::thread_local_inner!($(#[$attr])* $vis $name, $t, const $init);
|
2021-03-23 11:04:29 -07:00
|
|
|
);
|
|
|
|
|
|
2017-04-19 02:29:40 +00:00
|
|
|
// process multiple declarations
|
|
|
|
|
($(#[$attr:meta])* $vis:vis static $name:ident: $t:ty = $init:expr; $($rest:tt)*) => (
|
2023-04-26 21:02:29 +02:00
|
|
|
$crate::thread::local_impl::thread_local_inner!($(#[$attr])* $vis $name, $t, $init);
|
2018-11-01 14:17:39 -07:00
|
|
|
$crate::thread_local!($($rest)*);
|
2016-06-04 15:19:22 -04:00
|
|
|
);
|
|
|
|
|
|
2017-04-19 02:29:40 +00:00
|
|
|
// handle a single declaration
|
|
|
|
|
($(#[$attr:meta])* $vis:vis static $name:ident: $t:ty = $init:expr) => (
|
2023-04-26 21:02:29 +02:00
|
|
|
$crate::thread::local_impl::thread_local_inner!($(#[$attr])* $vis $name, $t, $init);
|
2015-05-27 23:24:27 -07:00
|
|
|
);
|
|
|
|
|
}
|
|
|
|
|
|
2017-07-10 19:26:11 -04:00
|
|
|
/// An error returned by [`LocalKey::try_with`](struct.LocalKey.html#method.try_with).
|
2018-02-27 17:00:01 +01:00
|
|
|
#[stable(feature = "thread_local_try_with", since = "1.26.0")]
|
2021-06-24 04:16:11 -04:00
|
|
|
#[non_exhaustive]
|
2019-06-03 18:20:38 +02:00
|
|
|
#[derive(Clone, Copy, Eq, PartialEq)]
|
2021-06-24 04:16:11 -04:00
|
|
|
pub struct AccessError;
|
2017-07-10 19:26:11 -04:00
|
|
|
|
2018-02-27 17:00:01 +01:00
|
|
|
#[stable(feature = "thread_local_try_with", since = "1.26.0")]
|
2017-07-10 19:26:11 -04:00
|
|
|
impl fmt::Debug for AccessError {
|
2019-03-01 09:34:11 +01:00
|
|
|
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
2017-07-10 19:26:11 -04:00
|
|
|
f.debug_struct("AccessError").finish()
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2018-02-27 17:00:01 +01:00
|
|
|
#[stable(feature = "thread_local_try_with", since = "1.26.0")]
|
2017-07-10 19:26:11 -04:00
|
|
|
impl fmt::Display for AccessError {
|
2019-03-01 09:34:11 +01:00
|
|
|
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
2017-07-10 19:26:11 -04:00
|
|
|
fmt::Display::fmt("already destroyed", f)
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2019-08-04 15:11:08 +02:00
|
|
|
#[stable(feature = "thread_local_try_with", since = "1.26.0")]
|
2019-06-03 18:20:38 +02:00
|
|
|
impl Error for AccessError {}
|
|
|
|
|
|
2015-03-20 00:46:13 -07:00
|
|
|
impl<T: 'static> LocalKey<T> {
|
2015-05-27 11:18:36 +03:00
|
|
|
#[doc(hidden)]
|
2019-11-27 10:29:00 -08:00
|
|
|
#[unstable(
|
|
|
|
|
feature = "thread_local_internals",
|
|
|
|
|
reason = "recently added to create a key",
|
2019-12-21 13:16:18 +02:00
|
|
|
issue = "none"
|
2019-11-27 10:29:00 -08:00
|
|
|
)]
|
2020-09-17 11:02:56 -07:00
|
|
|
#[rustc_const_unstable(feature = "thread_local_internals", issue = "none")]
|
2024-05-25 00:19:47 +02:00
|
|
|
pub const unsafe fn new(inner: fn(Option<&mut Option<T>>) -> *const T) -> LocalKey<T> {
|
2019-11-27 10:29:00 -08:00
|
|
|
LocalKey { inner }
|
2015-05-27 11:18:36 +03:00
|
|
|
}
|
|
|
|
|
|
2015-04-13 10:21:32 -04:00
|
|
|
/// Acquires a reference to the value in this TLS key.
|
2014-11-14 14:20:57 -08:00
|
|
|
///
|
|
|
|
|
/// This will lazily initialize the value if this thread has not referenced
|
|
|
|
|
/// this key yet.
|
|
|
|
|
///
|
|
|
|
|
/// # Panics
|
|
|
|
|
///
|
|
|
|
|
/// This function will `panic!()` if the key currently has its
|
|
|
|
|
/// destructor running, and it **may** panic if the destructor has
|
|
|
|
|
/// previously been run for this thread.
|
2015-01-23 21:48:20 -08:00
|
|
|
#[stable(feature = "rust1", since = "1.0.0")]
|
2014-12-10 07:49:45 -08:00
|
|
|
pub fn with<F, R>(&'static self, f: F) -> R
|
2019-11-27 10:29:00 -08:00
|
|
|
where
|
|
|
|
|
F: FnOnce(&T) -> R,
|
|
|
|
|
{
|
|
|
|
|
self.try_with(f).expect(
|
|
|
|
|
"cannot access a Thread Local Storage value \
|
|
|
|
|
during or after destruction",
|
|
|
|
|
)
|
2014-11-14 14:20:57 -08:00
|
|
|
}
|
|
|
|
|
|
2017-07-10 19:26:11 -04:00
|
|
|
/// Acquires a reference to the value in this TLS key.
|
|
|
|
|
///
|
|
|
|
|
/// This will lazily initialize the value if this thread has not referenced
|
|
|
|
|
/// this key yet. If the key has been destroyed (which may happen if this is called
|
2020-11-07 12:22:24 -08:00
|
|
|
/// in a destructor), this function will return an [`AccessError`].
|
2017-07-10 19:26:11 -04:00
|
|
|
///
|
|
|
|
|
/// # Panics
|
|
|
|
|
///
|
|
|
|
|
/// This function will still `panic!()` if the key is uninitialized and the
|
|
|
|
|
/// key's initializer panics.
|
2018-02-27 17:00:01 +01:00
|
|
|
#[stable(feature = "thread_local_try_with", since = "1.26.0")]
|
2020-03-30 14:36:28 +02:00
|
|
|
#[inline]
|
2017-07-10 19:26:11 -04:00
|
|
|
pub fn try_with<F, R>(&'static self, f: F) -> Result<R, AccessError>
|
2018-02-27 17:00:01 +01:00
|
|
|
where
|
|
|
|
|
F: FnOnce(&T) -> R,
|
|
|
|
|
{
|
2024-05-25 00:19:47 +02:00
|
|
|
let thread_local = unsafe { (self.inner)(None).as_ref().ok_or(AccessError)? };
|
2024-04-08 17:47:09 -04:00
|
|
|
Ok(f(thread_local))
|
2019-05-02 22:40:52 -07:00
|
|
|
}
|
2021-10-19 14:37:27 +02:00
|
|
|
|
2021-12-20 19:21:36 +01:00
|
|
|
/// Acquires a reference to the value in this TLS key, initializing it with
|
|
|
|
|
/// `init` if it wasn't already initialized on this thread.
|
|
|
|
|
///
|
|
|
|
|
/// If `init` was used to initialize the thread local variable, `None` is
|
|
|
|
|
/// passed as the first argument to `f`. If it was already initialized,
|
|
|
|
|
/// `Some(init)` is passed to `f`.
|
|
|
|
|
///
|
|
|
|
|
/// # Panics
|
|
|
|
|
///
|
|
|
|
|
/// This function will panic if the key currently has its destructor
|
|
|
|
|
/// running, and it **may** panic if the destructor has previously been run
|
|
|
|
|
/// for this thread.
|
2021-10-19 14:37:27 +02:00
|
|
|
fn initialize_with<F, R>(&'static self, init: T, f: F) -> R
|
|
|
|
|
where
|
|
|
|
|
F: FnOnce(Option<T>, &T) -> R,
|
|
|
|
|
{
|
2024-04-08 17:47:09 -04:00
|
|
|
let mut init = Some(init);
|
|
|
|
|
|
|
|
|
|
let reference = unsafe {
|
2024-05-25 00:19:47 +02:00
|
|
|
(self.inner)(Some(&mut init)).as_ref().expect(
|
2021-10-19 14:37:27 +02:00
|
|
|
"cannot access a Thread Local Storage value \
|
|
|
|
|
during or after destruction",
|
2024-04-08 17:47:09 -04:00
|
|
|
)
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
f(init, reference)
|
2021-10-19 14:37:27 +02:00
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
impl<T: 'static> LocalKey<Cell<T>> {
|
|
|
|
|
/// Sets or initializes the contained value.
|
|
|
|
|
///
|
|
|
|
|
/// Unlike the other methods, this will *not* run the lazy initializer of
|
|
|
|
|
/// the thread local. Instead, it will be directly initialized with the
|
|
|
|
|
/// given value if it wasn't initialized yet.
|
|
|
|
|
///
|
|
|
|
|
/// # Panics
|
|
|
|
|
///
|
|
|
|
|
/// Panics if the key currently has its destructor running,
|
|
|
|
|
/// and it **may** panic if the destructor has previously been run for this thread.
|
|
|
|
|
///
|
|
|
|
|
/// # Examples
|
|
|
|
|
///
|
|
|
|
|
/// ```
|
|
|
|
|
/// use std::cell::Cell;
|
|
|
|
|
///
|
|
|
|
|
/// thread_local! {
|
|
|
|
|
/// static X: Cell<i32> = panic!("!");
|
|
|
|
|
/// }
|
|
|
|
|
///
|
|
|
|
|
/// // Calling X.get() here would result in a panic.
|
|
|
|
|
///
|
|
|
|
|
/// X.set(123); // But X.set() is fine, as it skips the initializer above.
|
|
|
|
|
///
|
|
|
|
|
/// assert_eq!(X.get(), 123);
|
|
|
|
|
/// ```
|
2023-08-21 09:12:15 -04:00
|
|
|
#[stable(feature = "local_key_cell_methods", since = "1.73.0")]
|
2021-10-19 14:37:27 +02:00
|
|
|
pub fn set(&'static self, value: T) {
|
2021-12-20 19:21:36 +01:00
|
|
|
self.initialize_with(Cell::new(value), |value, cell| {
|
|
|
|
|
if let Some(value) = value {
|
|
|
|
|
// The cell was already initialized, so `value` wasn't used to
|
|
|
|
|
// initialize it. So we overwrite the current value with the
|
|
|
|
|
// new one instead.
|
|
|
|
|
cell.set(value.into_inner());
|
2021-10-19 14:37:27 +02:00
|
|
|
}
|
|
|
|
|
});
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/// Returns a copy of the contained value.
|
|
|
|
|
///
|
|
|
|
|
/// This will lazily initialize the value if this thread has not referenced
|
|
|
|
|
/// this key yet.
|
|
|
|
|
///
|
|
|
|
|
/// # Panics
|
|
|
|
|
///
|
|
|
|
|
/// Panics if the key currently has its destructor running,
|
|
|
|
|
/// and it **may** panic if the destructor has previously been run for this thread.
|
|
|
|
|
///
|
|
|
|
|
/// # Examples
|
|
|
|
|
///
|
|
|
|
|
/// ```
|
|
|
|
|
/// use std::cell::Cell;
|
|
|
|
|
///
|
|
|
|
|
/// thread_local! {
|
|
|
|
|
/// static X: Cell<i32> = Cell::new(1);
|
|
|
|
|
/// }
|
|
|
|
|
///
|
|
|
|
|
/// assert_eq!(X.get(), 1);
|
|
|
|
|
/// ```
|
2023-08-21 09:12:15 -04:00
|
|
|
#[stable(feature = "local_key_cell_methods", since = "1.73.0")]
|
2021-10-19 14:37:27 +02:00
|
|
|
pub fn get(&'static self) -> T
|
|
|
|
|
where
|
|
|
|
|
T: Copy,
|
|
|
|
|
{
|
2024-04-08 17:48:07 -04:00
|
|
|
self.with(Cell::get)
|
2021-10-19 14:37:27 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/// Takes the contained value, leaving `Default::default()` in its place.
|
|
|
|
|
///
|
|
|
|
|
/// This will lazily initialize the value if this thread has not referenced
|
|
|
|
|
/// this key yet.
|
|
|
|
|
///
|
|
|
|
|
/// # Panics
|
|
|
|
|
///
|
|
|
|
|
/// Panics if the key currently has its destructor running,
|
|
|
|
|
/// and it **may** panic if the destructor has previously been run for this thread.
|
|
|
|
|
///
|
|
|
|
|
/// # Examples
|
|
|
|
|
///
|
|
|
|
|
/// ```
|
|
|
|
|
/// use std::cell::Cell;
|
|
|
|
|
///
|
|
|
|
|
/// thread_local! {
|
|
|
|
|
/// static X: Cell<Option<i32>> = Cell::new(Some(1));
|
|
|
|
|
/// }
|
|
|
|
|
///
|
|
|
|
|
/// assert_eq!(X.take(), Some(1));
|
|
|
|
|
/// assert_eq!(X.take(), None);
|
|
|
|
|
/// ```
|
2023-08-21 09:12:15 -04:00
|
|
|
#[stable(feature = "local_key_cell_methods", since = "1.73.0")]
|
2021-10-19 14:37:27 +02:00
|
|
|
pub fn take(&'static self) -> T
|
|
|
|
|
where
|
|
|
|
|
T: Default,
|
|
|
|
|
{
|
2024-04-08 17:48:07 -04:00
|
|
|
self.with(Cell::take)
|
2021-10-19 14:37:27 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/// Replaces the contained value, returning the old value.
|
|
|
|
|
///
|
|
|
|
|
/// This will lazily initialize the value if this thread has not referenced
|
|
|
|
|
/// this key yet.
|
|
|
|
|
///
|
|
|
|
|
/// # Panics
|
|
|
|
|
///
|
|
|
|
|
/// Panics if the key currently has its destructor running,
|
|
|
|
|
/// and it **may** panic if the destructor has previously been run for this thread.
|
|
|
|
|
///
|
|
|
|
|
/// # Examples
|
|
|
|
|
///
|
|
|
|
|
/// ```
|
|
|
|
|
/// use std::cell::Cell;
|
|
|
|
|
///
|
|
|
|
|
/// thread_local! {
|
|
|
|
|
/// static X: Cell<i32> = Cell::new(1);
|
|
|
|
|
/// }
|
|
|
|
|
///
|
|
|
|
|
/// assert_eq!(X.replace(2), 1);
|
|
|
|
|
/// assert_eq!(X.replace(3), 2);
|
|
|
|
|
/// ```
|
2023-08-21 09:12:15 -04:00
|
|
|
#[stable(feature = "local_key_cell_methods", since = "1.73.0")]
|
2024-02-07 02:35:49 +00:00
|
|
|
#[rustc_confusables("swap")]
|
2021-10-19 14:37:27 +02:00
|
|
|
pub fn replace(&'static self, value: T) -> T {
|
|
|
|
|
self.with(|cell| cell.replace(value))
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
impl<T: 'static> LocalKey<RefCell<T>> {
|
|
|
|
|
/// Acquires a reference to the contained value.
|
|
|
|
|
///
|
|
|
|
|
/// This will lazily initialize the value if this thread has not referenced
|
|
|
|
|
/// this key yet.
|
|
|
|
|
///
|
|
|
|
|
/// # Panics
|
|
|
|
|
///
|
2021-12-20 19:21:36 +01:00
|
|
|
/// Panics if the value is currently mutably borrowed.
|
2021-10-19 14:37:27 +02:00
|
|
|
///
|
|
|
|
|
/// Panics if the key currently has its destructor running,
|
|
|
|
|
/// and it **may** panic if the destructor has previously been run for this thread.
|
|
|
|
|
///
|
|
|
|
|
/// # Example
|
|
|
|
|
///
|
|
|
|
|
/// ```
|
|
|
|
|
/// use std::cell::RefCell;
|
|
|
|
|
///
|
|
|
|
|
/// thread_local! {
|
|
|
|
|
/// static X: RefCell<Vec<i32>> = RefCell::new(Vec::new());
|
|
|
|
|
/// }
|
|
|
|
|
///
|
2021-12-20 13:38:07 +01:00
|
|
|
/// X.with_borrow(|v| assert!(v.is_empty()));
|
2021-10-19 14:37:27 +02:00
|
|
|
/// ```
|
2023-08-21 09:12:15 -04:00
|
|
|
#[stable(feature = "local_key_cell_methods", since = "1.73.0")]
|
2021-12-20 13:38:07 +01:00
|
|
|
pub fn with_borrow<F, R>(&'static self, f: F) -> R
|
2021-10-19 14:37:27 +02:00
|
|
|
where
|
|
|
|
|
F: FnOnce(&T) -> R,
|
|
|
|
|
{
|
2021-12-20 19:21:53 +01:00
|
|
|
self.with(|cell| f(&cell.borrow()))
|
2021-10-19 14:37:27 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/// Acquires a mutable reference to the contained value.
|
|
|
|
|
///
|
|
|
|
|
/// This will lazily initialize the value if this thread has not referenced
|
|
|
|
|
/// this key yet.
|
|
|
|
|
///
|
|
|
|
|
/// # Panics
|
|
|
|
|
///
|
|
|
|
|
/// Panics if the value is currently borrowed.
|
|
|
|
|
///
|
|
|
|
|
/// Panics if the key currently has its destructor running,
|
|
|
|
|
/// and it **may** panic if the destructor has previously been run for this thread.
|
|
|
|
|
///
|
|
|
|
|
/// # Example
|
|
|
|
|
///
|
|
|
|
|
/// ```
|
|
|
|
|
/// use std::cell::RefCell;
|
|
|
|
|
///
|
|
|
|
|
/// thread_local! {
|
|
|
|
|
/// static X: RefCell<Vec<i32>> = RefCell::new(Vec::new());
|
|
|
|
|
/// }
|
|
|
|
|
///
|
2021-12-20 13:38:07 +01:00
|
|
|
/// X.with_borrow_mut(|v| v.push(1));
|
2021-10-19 14:37:27 +02:00
|
|
|
///
|
2021-12-20 13:38:07 +01:00
|
|
|
/// X.with_borrow(|v| assert_eq!(*v, vec![1]));
|
2021-10-19 14:37:27 +02:00
|
|
|
/// ```
|
2023-08-21 09:12:15 -04:00
|
|
|
#[stable(feature = "local_key_cell_methods", since = "1.73.0")]
|
2021-12-20 13:38:07 +01:00
|
|
|
pub fn with_borrow_mut<F, R>(&'static self, f: F) -> R
|
2021-10-19 14:37:27 +02:00
|
|
|
where
|
|
|
|
|
F: FnOnce(&mut T) -> R,
|
|
|
|
|
{
|
|
|
|
|
self.with(|cell| f(&mut cell.borrow_mut()))
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/// Sets or initializes the contained value.
|
|
|
|
|
///
|
|
|
|
|
/// Unlike the other methods, this will *not* run the lazy initializer of
|
|
|
|
|
/// the thread local. Instead, it will be directly initialized with the
|
|
|
|
|
/// given value if it wasn't initialized yet.
|
|
|
|
|
///
|
|
|
|
|
/// # Panics
|
|
|
|
|
///
|
2021-12-20 19:21:36 +01:00
|
|
|
/// Panics if the value is currently borrowed.
|
|
|
|
|
///
|
2021-10-19 14:37:27 +02:00
|
|
|
/// Panics if the key currently has its destructor running,
|
|
|
|
|
/// and it **may** panic if the destructor has previously been run for this thread.
|
|
|
|
|
///
|
|
|
|
|
/// # Examples
|
|
|
|
|
///
|
|
|
|
|
/// ```
|
|
|
|
|
/// use std::cell::RefCell;
|
|
|
|
|
///
|
|
|
|
|
/// thread_local! {
|
|
|
|
|
/// static X: RefCell<Vec<i32>> = panic!("!");
|
|
|
|
|
/// }
|
|
|
|
|
///
|
|
|
|
|
/// // Calling X.with() here would result in a panic.
|
|
|
|
|
///
|
|
|
|
|
/// X.set(vec![1, 2, 3]); // But X.set() is fine, as it skips the initializer above.
|
|
|
|
|
///
|
2021-12-20 13:38:07 +01:00
|
|
|
/// X.with_borrow(|v| assert_eq!(*v, vec![1, 2, 3]));
|
2021-10-19 14:37:27 +02:00
|
|
|
/// ```
|
2023-08-21 09:12:15 -04:00
|
|
|
#[stable(feature = "local_key_cell_methods", since = "1.73.0")]
|
2021-10-19 14:37:27 +02:00
|
|
|
pub fn set(&'static self, value: T) {
|
2021-12-20 19:21:36 +01:00
|
|
|
self.initialize_with(RefCell::new(value), |value, cell| {
|
|
|
|
|
if let Some(value) = value {
|
|
|
|
|
// The cell was already initialized, so `value` wasn't used to
|
|
|
|
|
// initialize it. So we overwrite the current value with the
|
|
|
|
|
// new one instead.
|
2021-12-20 19:21:53 +01:00
|
|
|
*cell.borrow_mut() = value.into_inner();
|
2021-10-19 14:37:27 +02:00
|
|
|
}
|
|
|
|
|
});
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/// Takes the contained value, leaving `Default::default()` in its place.
|
|
|
|
|
///
|
|
|
|
|
/// This will lazily initialize the value if this thread has not referenced
|
|
|
|
|
/// this key yet.
|
|
|
|
|
///
|
|
|
|
|
/// # Panics
|
|
|
|
|
///
|
|
|
|
|
/// Panics if the value is currently borrowed.
|
|
|
|
|
///
|
|
|
|
|
/// Panics if the key currently has its destructor running,
|
|
|
|
|
/// and it **may** panic if the destructor has previously been run for this thread.
|
|
|
|
|
///
|
|
|
|
|
/// # Examples
|
|
|
|
|
///
|
|
|
|
|
/// ```
|
|
|
|
|
/// use std::cell::RefCell;
|
|
|
|
|
///
|
|
|
|
|
/// thread_local! {
|
|
|
|
|
/// static X: RefCell<Vec<i32>> = RefCell::new(Vec::new());
|
|
|
|
|
/// }
|
|
|
|
|
///
|
2021-12-20 13:38:07 +01:00
|
|
|
/// X.with_borrow_mut(|v| v.push(1));
|
2021-10-19 14:37:27 +02:00
|
|
|
///
|
|
|
|
|
/// let a = X.take();
|
|
|
|
|
///
|
|
|
|
|
/// assert_eq!(a, vec![1]);
|
|
|
|
|
///
|
2021-12-20 13:38:07 +01:00
|
|
|
/// X.with_borrow(|v| assert!(v.is_empty()));
|
2021-10-19 14:37:27 +02:00
|
|
|
/// ```
|
2023-08-21 09:12:15 -04:00
|
|
|
#[stable(feature = "local_key_cell_methods", since = "1.73.0")]
|
2021-10-19 14:37:27 +02:00
|
|
|
pub fn take(&'static self) -> T
|
|
|
|
|
where
|
|
|
|
|
T: Default,
|
|
|
|
|
{
|
2024-04-08 17:48:07 -04:00
|
|
|
self.with(RefCell::take)
|
2021-10-19 14:37:27 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/// Replaces the contained value, returning the old value.
|
|
|
|
|
///
|
|
|
|
|
/// # Panics
|
|
|
|
|
///
|
|
|
|
|
/// Panics if the value is currently borrowed.
|
|
|
|
|
///
|
|
|
|
|
/// Panics if the key currently has its destructor running,
|
|
|
|
|
/// and it **may** panic if the destructor has previously been run for this thread.
|
|
|
|
|
///
|
|
|
|
|
/// # Examples
|
|
|
|
|
///
|
|
|
|
|
/// ```
|
|
|
|
|
/// use std::cell::RefCell;
|
|
|
|
|
///
|
|
|
|
|
/// thread_local! {
|
|
|
|
|
/// static X: RefCell<Vec<i32>> = RefCell::new(Vec::new());
|
|
|
|
|
/// }
|
|
|
|
|
///
|
|
|
|
|
/// let prev = X.replace(vec![1, 2, 3]);
|
|
|
|
|
/// assert!(prev.is_empty());
|
|
|
|
|
///
|
2021-12-20 13:38:07 +01:00
|
|
|
/// X.with_borrow(|v| assert_eq!(*v, vec![1, 2, 3]));
|
2021-10-19 14:37:27 +02:00
|
|
|
/// ```
|
2023-08-21 09:12:15 -04:00
|
|
|
#[stable(feature = "local_key_cell_methods", since = "1.73.0")]
|
2024-02-07 02:35:49 +00:00
|
|
|
#[rustc_confusables("swap")]
|
2021-10-19 14:37:27 +02:00
|
|
|
pub fn replace(&'static self, value: T) -> T {
|
|
|
|
|
self.with(|cell| cell.replace(value))
|
|
|
|
|
}
|
2019-05-02 22:40:52 -07:00
|
|
|
}
|