1
Fork 0

Outline panicking code for LocalKey::with

See https://github.com/rust-lang/rust/pull/115491 for prior related
modifications.

https://godbolt.org/z/MTsz87jGj shows a reduction of the code size
for TLS accesses.
This commit is contained in:
Joseph Perez 2025-01-08 00:27:14 +01:00
parent ad211ced81
commit 8ec7bae57b
No known key found for this signature in database
GPG key ID: 837FB09BDC1A1531

View file

@ -230,6 +230,14 @@ impl fmt::Display for AccessError {
#[stable(feature = "thread_local_try_with", since = "1.26.0")] #[stable(feature = "thread_local_try_with", since = "1.26.0")]
impl Error for AccessError {} impl Error for AccessError {}
// This ensures the panicking code is outlined from `with` for `LocalKey`.
#[cfg_attr(not(feature = "panic_immediate_abort"), inline(never))]
#[track_caller]
#[cold]
fn panic_access_error(err: AccessError) -> ! {
panic!("cannot access a Thread Local Storage value during or after destruction: {err:?}")
}
impl<T: 'static> LocalKey<T> { impl<T: 'static> LocalKey<T> {
#[doc(hidden)] #[doc(hidden)]
#[unstable( #[unstable(
@ -269,10 +277,10 @@ impl<T: 'static> LocalKey<T> {
where where
F: FnOnce(&T) -> R, F: FnOnce(&T) -> R,
{ {
self.try_with(f).expect( match self.try_with(f) {
"cannot access a Thread Local Storage value \ Ok(r) => r,
during or after destruction", Err(err) => panic_access_error(err),
) }
} }
/// Acquires a reference to the value in this TLS key. /// Acquires a reference to the value in this TLS key.
@ -327,10 +335,10 @@ impl<T: 'static> LocalKey<T> {
let mut init = Some(init); let mut init = Some(init);
let reference = unsafe { let reference = unsafe {
(self.inner)(Some(&mut init)).as_ref().expect( match (self.inner)(Some(&mut init)).as_ref() {
"cannot access a Thread Local Storage value \ Some(r) => r,
during or after destruction", None => panic_access_error(AccessError),
) }
}; };
f(init, reference) f(init, reference)