Skip to content

Commit

Permalink
Reduce unsafe code in get_or
Browse files Browse the repository at this point in the history
get_or() currently works as a wrapper around get_or_try(). It wraps the
result of the passed function into a Result<T, ()> and then calls
unreachable_unchecked, which is an unsafe function. However, as an Err
branch is never instantiated for this Result type, we can use the
uninhabited Infallible type instead of the unit type. At this point it
is 100% safe to unwrap the underlying result and match on the
uninhabited error type to eliminate that branch.

It turns out this was the only time that the "unreachable" module was
used in the library, so I've also taken the liberty of deleting that
file.

Signed-off-by: John Nunley <dev@notgull.net>
  • Loading branch information
notgull committed Oct 11, 2023
1 parent faa4409 commit f37a6f1
Show file tree
Hide file tree
Showing 2 changed files with 4 additions and 62 deletions.
9 changes: 4 additions & 5 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -69,12 +69,12 @@

mod cached;
mod thread_id;
mod unreachable;

#[allow(deprecated)]
pub use cached::{CachedIntoIter, CachedIterMut, CachedThreadLocal};

use std::cell::UnsafeCell;
use std::convert::Infallible;
use std::fmt;
use std::iter::FusedIterator;
use std::mem;
Expand All @@ -83,7 +83,6 @@ use std::panic::UnwindSafe;
use std::ptr;
use std::sync::atomic::{AtomicBool, AtomicPtr, AtomicUsize, Ordering};
use thread_id::Thread;
use unreachable::UncheckedResultExt;

// Use usize::BITS once it has stabilized and the MSRV has been bumped.
#[cfg(target_pointer_width = "16")]
Expand Down Expand Up @@ -187,9 +186,9 @@ impl<T: Send> ThreadLocal<T> {
where
F: FnOnce() -> T,
{
unsafe {
self.get_or_try(|| Ok::<T, ()>(create()))
.unchecked_unwrap_ok()
match self.get_or_try(|| Ok::<T, Infallible>(create())) {
Ok(val) => val,
Err(inf) => match inf {},
}
}

Expand Down
57 changes: 0 additions & 57 deletions src/unreachable.rs

This file was deleted.

0 comments on commit f37a6f1

Please sign in to comment.