Skip to content

Commit

Permalink
Merge pull request #273 from briansmith/b/cold
Browse files Browse the repository at this point in the history
Make initialization in `OnceNonZeroUsize::get_or_try_init` `#[cold]`.
  • Loading branch information
matklad authored Feb 6, 2025
2 parents 4fbd4a5 + 1a885da commit d119eea
Show file tree
Hide file tree
Showing 4 changed files with 19 additions and 15 deletions.
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@

## Unreleased

- Outline initialization in `race`: [#273](https://github.com/matklad/once_cell/pull/273).

## 1.20.2

- Remove `portable_atomic` from Cargo.lock if it is not, in fact, used: [#267](https://github.com/matklad/once_cell/pull/267)
Expand Down
2 changes: 1 addition & 1 deletion Cargo.lock.msrv

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "once_cell"
version = "1.20.2"
version = "1.20.3"
authors = ["Aleksey Kladov <[email protected]>"]
license = "MIT OR Apache-2.0"
edition = "2021"
Expand Down
28 changes: 15 additions & 13 deletions src/race.rs
Original file line number Diff line number Diff line change
Expand Up @@ -93,19 +93,21 @@ impl OnceNonZeroUsize {
F: FnOnce() -> Result<NonZeroUsize, E>,
{
let val = self.inner.load(Ordering::Acquire);
let res = match NonZeroUsize::new(val) {
Some(it) => it,
None => {
let mut val = f()?.get();
let exchange =
self.inner.compare_exchange(0, val, Ordering::AcqRel, Ordering::Acquire);
if let Err(old) = exchange {
val = old;
}
unsafe { NonZeroUsize::new_unchecked(val) }
}
};
Ok(res)
match NonZeroUsize::new(val) {
Some(it) => Ok(it),
None => self.init(f),
}
}

#[cold]
#[inline(never)]
fn init<E>(&self, f: impl FnOnce() -> Result<NonZeroUsize, E>) -> Result<NonZeroUsize, E> {
let mut val = f()?.get();
let exchange = self.inner.compare_exchange(0, val, Ordering::AcqRel, Ordering::Acquire);
if let Err(old) = exchange {
val = old;
}
Ok(unsafe { NonZeroUsize::new_unchecked(val) })
}
}

Expand Down

0 comments on commit d119eea

Please sign in to comment.