Skip to content

Commit 2447a93

Browse files
authored
Merge pull request #281 from briansmith/b/init-inner
race: DRY `OnceNonZeroUsize::{init, set}` and `OnceNonZeroUsize::{get, get_or_try_init}`.
2 parents c294d64 + f695b56 commit 2447a93

File tree

1 file changed

+10
-8
lines changed

1 file changed

+10
-8
lines changed

src/race.rs

+10-8
Original file line numberDiff line numberDiff line change
@@ -105,9 +105,7 @@ impl OnceNonZeroUsize {
105105
/// full.
106106
#[inline]
107107
pub fn set(&self, value: NonZeroUsize) -> Result<(), ()> {
108-
let exchange =
109-
self.inner.compare_exchange(0, value.get(), Ordering::Release, Ordering::Acquire);
110-
match exchange {
108+
match self.compare_exchange(value) {
111109
Ok(_) => Ok(()),
112110
Err(_) => Err(()),
113111
}
@@ -141,8 +139,7 @@ impl OnceNonZeroUsize {
141139
where
142140
F: FnOnce() -> Result<NonZeroUsize, E>,
143141
{
144-
let val = self.inner.load(Ordering::Acquire);
145-
match NonZeroUsize::new(val) {
142+
match self.get() {
146143
Some(it) => Ok(it),
147144
None => self.init(f),
148145
}
@@ -151,13 +148,18 @@ impl OnceNonZeroUsize {
151148
#[cold]
152149
#[inline(never)]
153150
fn init<E>(&self, f: impl FnOnce() -> Result<NonZeroUsize, E>) -> Result<NonZeroUsize, E> {
154-
let mut val = f()?.get();
155-
let exchange = self.inner.compare_exchange(0, val, Ordering::Release, Ordering::Acquire);
156-
if let Err(old) = exchange {
151+
let nz = f()?;
152+
let mut val = nz.get();
153+
if let Err(old) = self.compare_exchange(nz) {
157154
val = old;
158155
}
159156
Ok(unsafe { NonZeroUsize::new_unchecked(val) })
160157
}
158+
159+
#[inline(always)]
160+
fn compare_exchange(&self, val: NonZeroUsize) -> Result<usize, usize> {
161+
self.inner.compare_exchange(0, val.get(), Ordering::Release, Ordering::Acquire)
162+
}
161163
}
162164

163165
/// A thread-safe cell which can be written to only once.

0 commit comments

Comments
 (0)