Skip to content

Commit 6e68a2f

Browse files
committed
Add SAFETY comments to the thread local implementation
Reduce `unsafe` block scope and add `SAFETY` comments.
1 parent 2aec2fe commit 6e68a2f

File tree

1 file changed

+12
-10
lines changed

1 file changed

+12
-10
lines changed

library/std/src/thread/local.rs

+12-10
Original file line numberDiff line numberDiff line change
@@ -281,10 +281,9 @@ impl<T: 'static> LocalKey<T> {
281281
where
282282
F: FnOnce(&T) -> R,
283283
{
284-
unsafe {
285-
let thread_local = (self.inner)(None).ok_or(AccessError)?;
286-
Ok(f(thread_local))
287-
}
284+
// SAFETY: `inner` is safe to call within the lifetime of the thread
285+
let thread_local = unsafe { (self.inner)(None).ok_or(AccessError)? };
286+
Ok(f(thread_local))
288287
}
289288

290289
/// Acquires a reference to the value in this TLS key, initializing it with
@@ -303,14 +302,17 @@ impl<T: 'static> LocalKey<T> {
303302
where
304303
F: FnOnce(Option<T>, &T) -> R,
305304
{
306-
unsafe {
307-
let mut init = Some(init);
308-
let reference = (self.inner)(Some(&mut init)).expect(
305+
let mut init = Some(init);
306+
307+
// SAFETY: `inner` is safe to call within the lifetime of the thread
308+
let reference = unsafe {
309+
(self.inner)(Some(&mut init)).expect(
309310
"cannot access a Thread Local Storage value \
310311
during or after destruction",
311-
);
312-
f(init, reference)
313-
}
312+
)
313+
};
314+
315+
f(init, reference)
314316
}
315317
}
316318

0 commit comments

Comments
 (0)