Skip to content

Commit b605c65

Browse files
committed
Auto merge of #135224 - wyfo:tls-panic-outline, r=cuviper
Outline panicking code for `LocalKey::with` See #115491 for prior related modifications. https://godbolt.org/z/MTsz87jGj shows a reduction of the code size for TLS accesses.
2 parents a42d5ec + 8ec7bae commit b605c65

File tree

1 file changed

+16
-8
lines changed

1 file changed

+16
-8
lines changed

library/std/src/thread/local.rs

+16-8
Original file line numberDiff line numberDiff line change
@@ -230,6 +230,14 @@ impl fmt::Display for AccessError {
230230
#[stable(feature = "thread_local_try_with", since = "1.26.0")]
231231
impl Error for AccessError {}
232232

233+
// This ensures the panicking code is outlined from `with` for `LocalKey`.
234+
#[cfg_attr(not(feature = "panic_immediate_abort"), inline(never))]
235+
#[track_caller]
236+
#[cold]
237+
fn panic_access_error(err: AccessError) -> ! {
238+
panic!("cannot access a Thread Local Storage value during or after destruction: {err:?}")
239+
}
240+
233241
impl<T: 'static> LocalKey<T> {
234242
#[doc(hidden)]
235243
#[unstable(
@@ -269,10 +277,10 @@ impl<T: 'static> LocalKey<T> {
269277
where
270278
F: FnOnce(&T) -> R,
271279
{
272-
self.try_with(f).expect(
273-
"cannot access a Thread Local Storage value \
274-
during or after destruction",
275-
)
280+
match self.try_with(f) {
281+
Ok(r) => r,
282+
Err(err) => panic_access_error(err),
283+
}
276284
}
277285

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

329337
let reference = unsafe {
330-
(self.inner)(Some(&mut init)).as_ref().expect(
331-
"cannot access a Thread Local Storage value \
332-
during or after destruction",
333-
)
338+
match (self.inner)(Some(&mut init)).as_ref() {
339+
Some(r) => r,
340+
None => panic_access_error(AccessError),
341+
}
334342
};
335343

336344
f(init, reference)

0 commit comments

Comments
 (0)