Skip to content

Commit

Permalink
use Option::unwrap_or_else fn to avoid some unsafe blocks
Browse files Browse the repository at this point in the history
(No is difference expected in terms of instructions executed, assuming unwrap is successful.)
  • Loading branch information
brodycj committed Sep 3, 2024
1 parent c63d9d0 commit ec93899
Show file tree
Hide file tree
Showing 3 changed files with 16 additions and 4 deletions.
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@

- propagate critical-section feature selection into portable-atomic
- cleaner internal result unwapping (should help keep newer MIRI versions happy)
- use `Option::unwrap_or_else` fn to avoid some unsafe blocks
(No is difference expected in terms of instructions executed, assuming unwrap is successful.)

## 1.19.0

Expand Down
4 changes: 3 additions & 1 deletion src/imp_std.rs
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,9 @@ impl<T> OnceCell<T> {
initialize_or_wait(
&self.queue,
Some(&mut || {
let f = unsafe { f.take().unwrap_unchecked() };
let f = f.take().unwrap_or_else(|| {
unreachable!();
});
match f() {
Ok(value) => {
unsafe { *slot = Some(value) };
Expand Down
14 changes: 11 additions & 3 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -559,7 +559,9 @@ pub mod unsync {
// checked that slot is currently `None`, so this write
// maintains the `inner`'s invariant.
*slot = Some(value);
Ok(unsafe { slot.as_ref().unwrap_unchecked() })
Ok(slot.as_ref().unwrap_or_else(|| {
unreachable!();
}))
}

/// Gets the contents of the cell, initializing it with `f`
Expand Down Expand Up @@ -630,7 +632,9 @@ pub mod unsync {
// `assert`, while keeping `set/get` would be sound, but it seems
// better to panic, rather than to silently use an old value.
assert!(self.set(val).is_ok(), "reentrant init");
Ok(unsafe { self.get().unwrap_unchecked() })
Ok(self.get().unwrap_or_else(|| {
unreachable!();
}))
}

/// Takes the value out of this `OnceCell`, moving it back to an uninitialized state.
Expand Down Expand Up @@ -1077,7 +1081,11 @@ pub mod sync {
/// ```
pub fn try_insert(&self, value: T) -> Result<&T, (&T, T)> {
let mut value = Some(value);
let res = self.get_or_init(|| unsafe { value.take().unwrap_unchecked() });
let res = self.get_or_init(|| {
value.take().unwrap_or_else(|| {
unreachable!();
})
});
match value {
None => Ok(res),
Some(value) => Err((res, value)),
Expand Down

0 comments on commit ec93899

Please sign in to comment.