Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 6 additions & 11 deletions library/std/src/sys/thread_local/native/lazy.rs
Original file line number Diff line number Diff line change
Expand Up @@ -56,27 +56,22 @@ where
/// The `self` reference must remain valid until the TLS destructor is run.
#[inline]
pub unsafe fn get_or_init(&self, i: Option<&mut Option<T>>, f: impl FnOnce() -> T) -> *const T {
if let State::Alive = self.state.get() {
self.value.get().cast()
} else {
unsafe { self.get_or_init_slow(i, f) }
match self.state.get() {
State::Alive => self.value.get().cast(),
State::Destroyed(_) => ptr::null(),
State::Uninitialized => unsafe { self.get_or_init_slow(i, f) },
}
}

/// # Safety
/// The `self` reference must remain valid until the TLS destructor is run.
/// * The state of `self` must be `Uninitalized`.
/// * The `self` reference must remain valid until the TLS destructor is run.
#[cold]
unsafe fn get_or_init_slow(
&self,
i: Option<&mut Option<T>>,
f: impl FnOnce() -> T,
) -> *const T {
match self.state.get() {
State::Uninitialized => {}
State::Alive => return self.value.get().cast(),
State::Destroyed(_) => return ptr::null(),
}

let v = i.and_then(Option::take).unwrap_or_else(f);

// SAFETY: we cannot be inside a `LocalKey::with` scope, as the initializer
Expand Down
17 changes: 6 additions & 11 deletions library/std/src/sys/thread_local/os.rs
Original file line number Diff line number Diff line change
Expand Up @@ -181,30 +181,25 @@ impl<T: 'static, const ALIGN: usize> Storage<T, ALIGN> {
pub fn get(&'static self, i: Option<&mut Option<T>>, f: impl FnOnce() -> T) -> *const T {
let key = self.key.force();
let ptr = unsafe { get(key) as *mut Value<T> };
if ptr.addr() > 1 {
match ptr.addr() {
// SAFETY: the check ensured the pointer is safe (its destructor
// is not running) + it is coming from a trusted source (self).
unsafe { &(*ptr).value }
} else {
2.. => unsafe { &(*ptr).value },
// destructor is running
1 => ptr::null(),
// SAFETY: trivially correct.
unsafe { Self::try_initialize(key, ptr, i, f) }
0 => unsafe { Self::try_initialize(key, i, f) },
}
}

/// # Safety
/// * `key` must be the result of calling `self.key.force()`
/// * `ptr` must be the current value associated with `key`.
/// * The current pointer associated with `key` must be null.
unsafe fn try_initialize(
key: Key,
ptr: *mut Value<T>,
i: Option<&mut Option<T>>,
f: impl FnOnce() -> T,
) -> *const T {
if ptr.addr() == 1 {
// destructor is running
return ptr::null();
}

let value = AlignedBox::<T, ALIGN>::new(Value {
value: i.and_then(Option::take).unwrap_or_else(f),
key,
Expand Down
Loading