Skip to content

Commit a851cc4

Browse files
committed
Mark initialization of OnceRef::get_or_try_init cold.
Use `Self::get()` instead of directly loading the value, which is a DRY improvement in its own right. Then it is trivial to split out the initialization into a `#[cold]` function, matching the other implementations in the module. This is the `OnceRef` analog of commit 90da60b.
1 parent 2447a93 commit a851cc4

File tree

1 file changed

+18
-13
lines changed

1 file changed

+18
-13
lines changed

src/race.rs

+18-13
Original file line numberDiff line numberDiff line change
@@ -303,20 +303,25 @@ impl<'a, T> OnceRef<'a, T> {
303303
where
304304
F: FnOnce() -> Result<&'a T, E>,
305305
{
306-
let mut ptr = self.inner.load(Ordering::Acquire);
306+
match self.get() {
307+
Some(val) => Ok(val),
308+
None => self.init(f),
309+
}
310+
}
307311

308-
if ptr.is_null() {
309-
let value: &'a T = f()?;
310-
ptr = <*const T>::cast_mut(value);
311-
let exchange = self.inner.compare_exchange(
312-
ptr::null_mut(),
313-
ptr,
314-
Ordering::Release,
315-
Ordering::Acquire,
316-
);
317-
if let Err(old) = exchange {
318-
ptr = old;
319-
}
312+
#[cold]
313+
#[inline(never)]
314+
fn init<E>(&self, f: impl FnOnce() -> Result<&'a T, E>) -> Result<&'a T, E> {
315+
let value: &'a T = f()?;
316+
let mut ptr = <*const T>::cast_mut(value);
317+
let exchange = self.inner.compare_exchange(
318+
ptr::null_mut(),
319+
ptr,
320+
Ordering::Release,
321+
Ordering::Acquire,
322+
);
323+
if let Err(old) = exchange {
324+
ptr = old;
320325
}
321326

322327
Ok(unsafe { &*ptr })

0 commit comments

Comments
 (0)