Skip to content

Commit

Permalink
Outline panicking code for LocalKey::with
Browse files Browse the repository at this point in the history
See #115491 for prior related
modifications.

https://godbolt.org/z/MTsz87jGj shows a reduction of the code size
for TLS accesses.
  • Loading branch information
wyfo committed Jan 7, 2025
1 parent ad211ce commit 8ec7bae
Showing 1 changed file with 16 additions and 8 deletions.
24 changes: 16 additions & 8 deletions library/std/src/thread/local.rs
Original file line number Diff line number Diff line change
Expand Up @@ -230,6 +230,14 @@ impl fmt::Display for AccessError {
#[stable(feature = "thread_local_try_with", since = "1.26.0")]
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> {
#[doc(hidden)]
#[unstable(
Expand Down Expand Up @@ -269,10 +277,10 @@ impl<T: 'static> LocalKey<T> {
where
F: FnOnce(&T) -> R,
{
self.try_with(f).expect(
"cannot access a Thread Local Storage value \
during or after destruction",
)
match self.try_with(f) {
Ok(r) => r,
Err(err) => panic_access_error(err),
}
}

/// Acquires a reference to the value in this TLS key.
Expand Down Expand Up @@ -327,10 +335,10 @@ impl<T: 'static> LocalKey<T> {
let mut init = Some(init);

let reference = unsafe {
(self.inner)(Some(&mut init)).as_ref().expect(
"cannot access a Thread Local Storage value \
during or after destruction",
)
match (self.inner)(Some(&mut init)).as_ref() {
Some(r) => r,
None => panic_access_error(AccessError),
}
};

f(init, reference)
Expand Down

0 comments on commit 8ec7bae

Please sign in to comment.