Skip to content

Commit 97d49fc

Browse files
committed
core: use pointer::write to cleanup LazyCell initialization
1 parent c7f9739 commit 97d49fc

File tree

1 file changed

+7
-8
lines changed

1 file changed

+7
-8
lines changed

library/core/src/cell/lazy.rs

+7-8
Original file line numberDiff line numberDiff line change
@@ -115,16 +115,15 @@ impl<T, F: FnOnce() -> T> LazyCell<T, F> {
115115
// SAFETY:
116116
// If the closure accessed the cell through something like a reentrant
117117
// mutex, but caught the panic resulting from the state being poisoned,
118-
// the mutable borrow for `state` will be invalidated, so create a new
119-
// one here.
120-
let state = unsafe { &mut *this.state.get() };
121-
*state = State::Init(data);
118+
// the mutable borrow for `state` will be invalidated, so we need to
119+
// go through the `UnsafeCell` pointer here. The state can only be
120+
// poisoned at this point, so using `write` to skip the destructor
121+
// of `State` should help the optimizer.
122+
unsafe { this.state.get().write(State::Init(data)) };
122123

123124
// SAFETY:
124-
// A reference obtained by downcasting from the mutable borrow would
125-
// become stale the next time `force` is called (since there is a conflict
126-
// between the mutable reference here and the shared reference there).
127-
// Do a new shared borrow of the state instead.
125+
// The previous references were invalidated by the `write` call above,
126+
// so do a new shared borrow of the state instead.
128127
let state = unsafe { &*this.state.get() };
129128
let State::Init(data) = state else { unreachable!() };
130129
data

0 commit comments

Comments
 (0)