2014-11-14 22:20:57 +00:00
|
|
|
//! Thread local storage
|
2015-03-20 07:46:13 +00:00
|
|
|
|
2019-12-21 11:16:18 +00:00
|
|
|
#![unstable(feature = "thread_local_internals", issue = "none")]
|
2014-11-14 22:20:57 +00: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 12:37:27 +00:00
|
|
|
use crate::cell::{Cell, RefCell};
|
2019-06-03 16:20:38 +00:00
|
|
|
use crate::error::Error;
|
2019-02-10 19:23:21 +00:00
|
|
|
use crate::fmt;
|
2014-11-14 22:20:57 +00: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 18:06:54 +00:00
|
|
|
/// target platform. It is instantiated with the [`thread_local!`] macro and the
|
|
|
|
/// primary method is the [`with`] method.
|
2014-11-14 22:20:57 +00:00
|
|
|
///
|
2017-05-14 18:06:54 +00:00
|
|
|
/// The [`with`] method yields a reference to the contained value which cannot be
|
2015-05-08 15:12:29 +00:00
|
|
|
/// sent across threads or escape the given closure.
|
2014-11-14 22:20:57 +00:00
|
|
|
///
|
2022-04-30 21:02:34 +00:00
|
|
|
/// [`thread_local!`]: crate::thread_local
|
|
|
|
///
|
2014-11-14 22:20:57 +00:00
|
|
|
/// # Initialization and Destruction
|
|
|
|
///
|
2017-05-14 18:06:54 +00:00
|
|
|
/// Initialization is dynamically performed on the first call to [`with`]
|
|
|
|
/// within a thread, and values that implement [`Drop`] get destructed when a
|
2017-02-15 22:26:29 +00:00
|
|
|
/// thread exits. Some caveats apply, which are explained below.
|
2014-11-14 22:20:57 +00:00
|
|
|
///
|
2017-09-07 19:57:08 +00:00
|
|
|
/// A `LocalKey`'s initializer cannot recursively depend on itself, and using
|
|
|
|
/// a `LocalKey` in this way will cause the initializer to infinitely recurse
|
|
|
|
/// on the first call to `with`.
|
|
|
|
///
|
2015-03-12 01:11:40 +00:00
|
|
|
/// # Examples
|
2014-11-14 22:20:57 +00:00
|
|
|
///
|
|
|
|
/// ```
|
|
|
|
/// use std::cell::RefCell;
|
2015-02-17 23:10:25 +00:00
|
|
|
/// use std::thread;
|
2014-11-14 22:20:57 +00:00
|
|
|
///
|
2015-02-23 16:24:50 +00:00
|
|
|
/// thread_local!(static FOO: RefCell<u32> = RefCell::new(1));
|
2014-11-14 22:20:57 +00:00
|
|
|
///
|
|
|
|
/// FOO.with(|f| {
|
|
|
|
/// assert_eq!(*f.borrow(), 1);
|
|
|
|
/// *f.borrow_mut() = 2;
|
|
|
|
/// });
|
|
|
|
///
|
|
|
|
/// // each thread starts out with the initial value of 1
|
2019-03-03 14:21:52 +00:00
|
|
|
/// let t = thread::spawn(move|| {
|
2014-11-14 22:20:57 +00:00
|
|
|
/// FOO.with(|f| {
|
|
|
|
/// assert_eq!(*f.borrow(), 1);
|
|
|
|
/// *f.borrow_mut() = 3;
|
|
|
|
/// });
|
2015-01-06 05:59:45 +00:00
|
|
|
/// });
|
2014-11-14 22:20:57 +00:00
|
|
|
///
|
2019-03-03 14:21:52 +00:00
|
|
|
/// // wait for the thread to complete and bail out on panic
|
|
|
|
/// t.join().unwrap();
|
|
|
|
///
|
2014-11-14 22:20:57 +00:00
|
|
|
/// // we retain our original value of 2 despite the child thread
|
|
|
|
/// FOO.with(|f| {
|
|
|
|
/// assert_eq!(*f.borrow(), 2);
|
|
|
|
/// });
|
|
|
|
/// ```
|
2016-01-29 21:46:47 +00:00
|
|
|
///
|
|
|
|
/// # Platform-specific behavior
|
|
|
|
///
|
|
|
|
/// Note that a "best effort" is made to ensure that destructors for types
|
2016-04-25 20:01:19 +00:00
|
|
|
/// stored in thread local storage are run, but not all platforms can guarantee
|
2016-01-29 21:46:47 +00: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 18:06:54 +00: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 20:03:00 +00:00
|
|
|
/// [`with`]: LocalKey::with
|
2022-09-27 11:06:31 +00:00
|
|
|
#[cfg_attr(not(test), rustc_diagnostic_item = "LocalKey")]
|
2015-01-24 05:48:20 +00:00
|
|
|
#[stable(feature = "rust1", since = "1.0.0")]
|
2015-12-11 20:42:29 +00: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 15:22:51 +00:00
|
|
|
// here is actually slightly shorter than the currently running thread!
|
2014-11-14 22:20:57 +00:00
|
|
|
//
|
2015-12-11 20:42:29 +00: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.
|
2021-10-19 12:37:27 +00:00
|
|
|
inner: unsafe fn(Option<&mut Option<T>>) -> Option<&'static T>,
|
2014-11-14 17:18:10 +00:00
|
|
|
}
|
2014-11-14 22:20:57 +00:00
|
|
|
|
2017-01-29 13:31:47 +00:00
|
|
|
#[stable(feature = "std_debug", since = "1.16.0")]
|
2016-11-25 18:21:49 +00:00
|
|
|
impl<T: 'static> fmt::Debug for LocalKey<T> {
|
2019-03-01 08:34:11 +00:00
|
|
|
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
2021-04-05 11:31:11 +00:00
|
|
|
f.debug_struct("LocalKey").finish_non_exhaustive()
|
2016-11-25 18:21:49 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2017-05-14 18:06:54 +00:00
|
|
|
/// Declare a new thread local storage key of type [`std::thread::LocalKey`].
|
2015-05-27 08:18:36 +00:00
|
|
|
///
|
2016-06-04 19:19:22 +00:00
|
|
|
/// # Syntax
|
|
|
|
///
|
|
|
|
/// The macro wraps any number of static declarations and makes them thread local.
|
2017-04-01 03:06:34 +00:00
|
|
|
/// Publicity and attributes for each static are allowed. Example:
|
2016-06-04 19:19:22 +00:00
|
|
|
///
|
|
|
|
/// ```
|
|
|
|
/// use std::cell::RefCell;
|
|
|
|
/// thread_local! {
|
|
|
|
/// pub static FOO: RefCell<u32> = RefCell::new(1);
|
|
|
|
///
|
|
|
|
/// #[allow(unused)]
|
|
|
|
/// static BAR: RefCell<f32> = RefCell::new(1.0);
|
|
|
|
/// }
|
|
|
|
/// # fn main() {}
|
|
|
|
/// ```
|
|
|
|
///
|
2020-08-20 20:03:00 +00:00
|
|
|
/// See [`LocalKey` documentation][`std::thread::LocalKey`] for more
|
2015-05-28 06:24:27 +00:00
|
|
|
/// information.
|
2017-05-14 18:06:54 +00:00
|
|
|
///
|
2020-08-20 20:03:00 +00:00
|
|
|
/// [`std::thread::LocalKey`]: crate::thread::LocalKey
|
2014-11-14 22:20:57 +00:00
|
|
|
#[macro_export]
|
2015-05-27 08:18:36 +00: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 23:58:12 +00:00
|
|
|
#[allow_internal_unstable(thread_local_internals)]
|
2015-05-28 06:24:27 +00:00
|
|
|
macro_rules! thread_local {
|
2017-04-01 03:06:34 +00:00
|
|
|
// empty (base case for the recursion)
|
2016-06-04 19:19:22 +00:00
|
|
|
() => {};
|
|
|
|
|
2021-03-23 18:04:29 +00:00
|
|
|
($(#[$attr:meta])* $vis:vis static $name:ident: $t:ty = const { $init:expr }; $($rest:tt)*) => (
|
|
|
|
$crate::__thread_local_inner!($(#[$attr])* $vis $name, $t, const $init);
|
|
|
|
$crate::thread_local!($($rest)*);
|
|
|
|
);
|
|
|
|
|
|
|
|
($(#[$attr:meta])* $vis:vis static $name:ident: $t:ty = const { $init:expr }) => (
|
|
|
|
$crate::__thread_local_inner!($(#[$attr])* $vis $name, $t, const $init);
|
|
|
|
);
|
|
|
|
|
2017-04-19 02:29:40 +00:00
|
|
|
// process multiple declarations
|
|
|
|
($(#[$attr:meta])* $vis:vis static $name:ident: $t:ty = $init:expr; $($rest:tt)*) => (
|
2018-11-01 21:17:39 +00:00
|
|
|
$crate::__thread_local_inner!($(#[$attr])* $vis $name, $t, $init);
|
|
|
|
$crate::thread_local!($($rest)*);
|
2016-06-04 19:19:22 +00:00
|
|
|
);
|
|
|
|
|
2017-04-19 02:29:40 +00:00
|
|
|
// handle a single declaration
|
|
|
|
($(#[$attr:meta])* $vis:vis static $name:ident: $t:ty = $init:expr) => (
|
2018-11-01 21:17:39 +00:00
|
|
|
$crate::__thread_local_inner!($(#[$attr])* $vis $name, $t, $init);
|
2015-05-28 06:24:27 +00:00
|
|
|
);
|
|
|
|
}
|
|
|
|
|
2017-07-10 23:26:11 +00:00
|
|
|
/// An error returned by [`LocalKey::try_with`](struct.LocalKey.html#method.try_with).
|
2018-02-27 16:00:01 +00:00
|
|
|
#[stable(feature = "thread_local_try_with", since = "1.26.0")]
|
2021-06-24 08:16:11 +00:00
|
|
|
#[non_exhaustive]
|
2019-06-03 16:20:38 +00:00
|
|
|
#[derive(Clone, Copy, Eq, PartialEq)]
|
2021-06-24 08:16:11 +00:00
|
|
|
pub struct AccessError;
|
2017-07-10 23:26:11 +00:00
|
|
|
|
2018-02-27 16:00:01 +00:00
|
|
|
#[stable(feature = "thread_local_try_with", since = "1.26.0")]
|
2017-07-10 23:26:11 +00:00
|
|
|
impl fmt::Debug for AccessError {
|
2019-03-01 08:34:11 +00:00
|
|
|
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
2017-07-10 23:26:11 +00:00
|
|
|
f.debug_struct("AccessError").finish()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-02-27 16:00:01 +00:00
|
|
|
#[stable(feature = "thread_local_try_with", since = "1.26.0")]
|
2017-07-10 23:26:11 +00:00
|
|
|
impl fmt::Display for AccessError {
|
2019-03-01 08:34:11 +00:00
|
|
|
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
2017-07-10 23:26:11 +00:00
|
|
|
fmt::Display::fmt("already destroyed", f)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-08-04 13:11:08 +00:00
|
|
|
#[stable(feature = "thread_local_try_with", since = "1.26.0")]
|
2019-06-03 16:20:38 +00:00
|
|
|
impl Error for AccessError {}
|
|
|
|
|
2015-03-20 07:46:13 +00:00
|
|
|
impl<T: 'static> LocalKey<T> {
|
2015-05-27 08:18:36 +00:00
|
|
|
#[doc(hidden)]
|
2019-11-27 18:29:00 +00:00
|
|
|
#[unstable(
|
|
|
|
feature = "thread_local_internals",
|
|
|
|
reason = "recently added to create a key",
|
2019-12-21 11:16:18 +00:00
|
|
|
issue = "none"
|
2019-11-27 18:29:00 +00:00
|
|
|
)]
|
2020-09-17 18:02:56 +00:00
|
|
|
#[rustc_const_unstable(feature = "thread_local_internals", issue = "none")]
|
2021-10-19 12:37:27 +00:00
|
|
|
pub const unsafe fn new(
|
|
|
|
inner: unsafe fn(Option<&mut Option<T>>) -> Option<&'static T>,
|
|
|
|
) -> LocalKey<T> {
|
2019-11-27 18:29:00 +00:00
|
|
|
LocalKey { inner }
|
2015-05-27 08:18:36 +00:00
|
|
|
}
|
|
|
|
|
2015-04-13 14:21:32 +00:00
|
|
|
/// Acquires a reference to the value in this TLS key.
|
2014-11-14 22:20:57 +00: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-24 05:48:20 +00:00
|
|
|
#[stable(feature = "rust1", since = "1.0.0")]
|
2014-12-10 15:49:45 +00:00
|
|
|
pub fn with<F, R>(&'static self, f: F) -> R
|
2019-11-27 18:29:00 +00: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 22:20:57 +00:00
|
|
|
}
|
|
|
|
|
2017-07-10 23:26:11 +00: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 20:22:24 +00:00
|
|
|
/// in a destructor), this function will return an [`AccessError`].
|
2017-07-10 23:26:11 +00:00
|
|
|
///
|
|
|
|
/// # Panics
|
|
|
|
///
|
|
|
|
/// This function will still `panic!()` if the key is uninitialized and the
|
|
|
|
/// key's initializer panics.
|
2018-02-27 16:00:01 +00:00
|
|
|
#[stable(feature = "thread_local_try_with", since = "1.26.0")]
|
2020-03-30 12:36:28 +00:00
|
|
|
#[inline]
|
2017-07-10 23:26:11 +00:00
|
|
|
pub fn try_with<F, R>(&'static self, f: F) -> Result<R, AccessError>
|
2018-02-27 16:00:01 +00:00
|
|
|
where
|
|
|
|
F: FnOnce(&T) -> R,
|
|
|
|
{
|
2017-07-10 23:26:11 +00:00
|
|
|
unsafe {
|
2021-10-19 12:37:27 +00:00
|
|
|
let thread_local = (self.inner)(None).ok_or(AccessError)?;
|
2019-05-03 05:40:52 +00:00
|
|
|
Ok(f(thread_local))
|
|
|
|
}
|
|
|
|
}
|
2021-10-19 12:37:27 +00:00
|
|
|
|
2021-12-20 18:21:36 +00: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 12:37:27 +00:00
|
|
|
fn initialize_with<F, R>(&'static self, init: T, f: F) -> R
|
|
|
|
where
|
|
|
|
F: FnOnce(Option<T>, &T) -> R,
|
|
|
|
{
|
|
|
|
unsafe {
|
|
|
|
let mut init = Some(init);
|
|
|
|
let reference = (self.inner)(Some(&mut init)).expect(
|
|
|
|
"cannot access a Thread Local Storage value \
|
|
|
|
during or after destruction",
|
|
|
|
);
|
|
|
|
f(init, reference)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
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
|
|
|
|
///
|
|
|
|
/// ```
|
|
|
|
/// #![feature(local_key_cell_methods)]
|
|
|
|
/// 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);
|
|
|
|
/// ```
|
2021-12-20 12:49:10 +00:00
|
|
|
#[unstable(feature = "local_key_cell_methods", issue = "92122")]
|
2021-10-19 12:37:27 +00:00
|
|
|
pub fn set(&'static self, value: T) {
|
2021-12-20 18:21:36 +00: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 12:37:27 +00: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
|
|
|
|
///
|
|
|
|
/// ```
|
|
|
|
/// #![feature(local_key_cell_methods)]
|
|
|
|
/// use std::cell::Cell;
|
|
|
|
///
|
|
|
|
/// thread_local! {
|
|
|
|
/// static X: Cell<i32> = Cell::new(1);
|
|
|
|
/// }
|
|
|
|
///
|
|
|
|
/// assert_eq!(X.get(), 1);
|
|
|
|
/// ```
|
2021-12-20 12:49:10 +00:00
|
|
|
#[unstable(feature = "local_key_cell_methods", issue = "92122")]
|
2021-10-19 12:37:27 +00:00
|
|
|
pub fn get(&'static self) -> T
|
|
|
|
where
|
|
|
|
T: Copy,
|
|
|
|
{
|
|
|
|
self.with(|cell| cell.get())
|
|
|
|
}
|
|
|
|
|
|
|
|
/// 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
|
|
|
|
///
|
|
|
|
/// ```
|
|
|
|
/// #![feature(local_key_cell_methods)]
|
|
|
|
/// 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);
|
|
|
|
/// ```
|
2021-12-20 12:49:10 +00:00
|
|
|
#[unstable(feature = "local_key_cell_methods", issue = "92122")]
|
2021-10-19 12:37:27 +00:00
|
|
|
pub fn take(&'static self) -> T
|
|
|
|
where
|
|
|
|
T: Default,
|
|
|
|
{
|
|
|
|
self.with(|cell| cell.take())
|
|
|
|
}
|
|
|
|
|
|
|
|
/// 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
|
|
|
|
///
|
|
|
|
/// ```
|
|
|
|
/// #![feature(local_key_cell_methods)]
|
|
|
|
/// 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);
|
|
|
|
/// ```
|
2021-12-20 12:49:10 +00:00
|
|
|
#[unstable(feature = "local_key_cell_methods", issue = "92122")]
|
2021-10-19 12:37:27 +00: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 18:21:36 +00:00
|
|
|
/// Panics if the value is currently mutably borrowed.
|
2021-10-19 12:37:27 +00: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
|
|
|
|
///
|
|
|
|
/// ```
|
|
|
|
/// #![feature(local_key_cell_methods)]
|
|
|
|
/// use std::cell::RefCell;
|
|
|
|
///
|
|
|
|
/// thread_local! {
|
|
|
|
/// static X: RefCell<Vec<i32>> = RefCell::new(Vec::new());
|
|
|
|
/// }
|
|
|
|
///
|
2021-12-20 12:38:07 +00:00
|
|
|
/// X.with_borrow(|v| assert!(v.is_empty()));
|
2021-10-19 12:37:27 +00:00
|
|
|
/// ```
|
2021-12-20 12:49:10 +00:00
|
|
|
#[unstable(feature = "local_key_cell_methods", issue = "92122")]
|
2021-12-20 12:38:07 +00:00
|
|
|
pub fn with_borrow<F, R>(&'static self, f: F) -> R
|
2021-10-19 12:37:27 +00:00
|
|
|
where
|
|
|
|
F: FnOnce(&T) -> R,
|
|
|
|
{
|
2021-12-20 18:21:53 +00:00
|
|
|
self.with(|cell| f(&cell.borrow()))
|
2021-10-19 12:37:27 +00: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
|
|
|
|
///
|
|
|
|
/// ```
|
|
|
|
/// #![feature(local_key_cell_methods)]
|
|
|
|
/// use std::cell::RefCell;
|
|
|
|
///
|
|
|
|
/// thread_local! {
|
|
|
|
/// static X: RefCell<Vec<i32>> = RefCell::new(Vec::new());
|
|
|
|
/// }
|
|
|
|
///
|
2021-12-20 12:38:07 +00:00
|
|
|
/// X.with_borrow_mut(|v| v.push(1));
|
2021-10-19 12:37:27 +00:00
|
|
|
///
|
2021-12-20 12:38:07 +00:00
|
|
|
/// X.with_borrow(|v| assert_eq!(*v, vec![1]));
|
2021-10-19 12:37:27 +00:00
|
|
|
/// ```
|
2021-12-20 12:49:10 +00:00
|
|
|
#[unstable(feature = "local_key_cell_methods", issue = "92122")]
|
2021-12-20 12:38:07 +00:00
|
|
|
pub fn with_borrow_mut<F, R>(&'static self, f: F) -> R
|
2021-10-19 12:37:27 +00: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 18:21:36 +00:00
|
|
|
/// Panics if the value is currently borrowed.
|
|
|
|
///
|
2021-10-19 12:37:27 +00: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
|
|
|
|
///
|
|
|
|
/// ```
|
|
|
|
/// #![feature(local_key_cell_methods)]
|
|
|
|
/// 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 12:38:07 +00:00
|
|
|
/// X.with_borrow(|v| assert_eq!(*v, vec![1, 2, 3]));
|
2021-10-19 12:37:27 +00:00
|
|
|
/// ```
|
2021-12-20 12:49:10 +00:00
|
|
|
#[unstable(feature = "local_key_cell_methods", issue = "92122")]
|
2021-10-19 12:37:27 +00:00
|
|
|
pub fn set(&'static self, value: T) {
|
2021-12-20 18:21:36 +00: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 18:21:53 +00:00
|
|
|
*cell.borrow_mut() = value.into_inner();
|
2021-10-19 12:37:27 +00: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
|
|
|
|
///
|
|
|
|
/// ```
|
|
|
|
/// #![feature(local_key_cell_methods)]
|
|
|
|
/// use std::cell::RefCell;
|
|
|
|
///
|
|
|
|
/// thread_local! {
|
|
|
|
/// static X: RefCell<Vec<i32>> = RefCell::new(Vec::new());
|
|
|
|
/// }
|
|
|
|
///
|
2021-12-20 12:38:07 +00:00
|
|
|
/// X.with_borrow_mut(|v| v.push(1));
|
2021-10-19 12:37:27 +00:00
|
|
|
///
|
|
|
|
/// let a = X.take();
|
|
|
|
///
|
|
|
|
/// assert_eq!(a, vec![1]);
|
|
|
|
///
|
2021-12-20 12:38:07 +00:00
|
|
|
/// X.with_borrow(|v| assert!(v.is_empty()));
|
2021-10-19 12:37:27 +00:00
|
|
|
/// ```
|
2021-12-20 12:49:10 +00:00
|
|
|
#[unstable(feature = "local_key_cell_methods", issue = "92122")]
|
2021-10-19 12:37:27 +00:00
|
|
|
pub fn take(&'static self) -> T
|
|
|
|
where
|
|
|
|
T: Default,
|
|
|
|
{
|
|
|
|
self.with(|cell| cell.take())
|
|
|
|
}
|
|
|
|
|
|
|
|
/// 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
|
|
|
|
///
|
|
|
|
/// ```
|
|
|
|
/// #![feature(local_key_cell_methods)]
|
|
|
|
/// 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 12:38:07 +00:00
|
|
|
/// X.with_borrow(|v| assert_eq!(*v, vec![1, 2, 3]));
|
2021-10-19 12:37:27 +00:00
|
|
|
/// ```
|
2021-12-20 12:49:10 +00:00
|
|
|
#[unstable(feature = "local_key_cell_methods", issue = "92122")]
|
2021-10-19 12:37:27 +00:00
|
|
|
pub fn replace(&'static self, value: T) -> T {
|
|
|
|
self.with(|cell| cell.replace(value))
|
|
|
|
}
|
2019-05-03 05:40:52 +00:00
|
|
|
}
|