about summary refs log tree commit diff
diff options
context:
space:
mode:
authorMatthias Krüger <matthias.krueger@famsik.de>2024-03-27 23:27:25 +0100
committerGitHub <noreply@github.com>2024-03-27 23:27:25 +0100
commit9c91e2cd8464ec1cdcc67f67704ebcf1ae51655f (patch)
tree17002d1c46d86b54de4a8d5ac8ed165af4f4c329
parentea7789c56e61a91063035e2af685fcbbdd7c127b (diff)
parent336ff42367aa375bba85bf5dbbea535b3c04d929 (diff)
downloadrust-9c91e2cd8464ec1cdcc67f67704ebcf1ae51655f.tar.gz
rust-9c91e2cd8464ec1cdcc67f67704ebcf1ae51655f.zip
Rollup merge of #123139 - scottmcm:simpler-nonzero-get, r=jhpratt
`num::NonZero::get` can be 1 transmute instead of 2

Just something I noticed in passing.  No need for a `match` in here to call `unreachable_unchecked`, as `transmute_unchecked` will add the appropriate `llvm.assume` <https://rust.godbolt.org/z/W5hjeETnc>.
-rw-r--r--library/core/src/num/nonzero.rs26
1 files changed, 14 insertions, 12 deletions
diff --git a/library/core/src/num/nonzero.rs b/library/core/src/num/nonzero.rs
index c65ffbb98f2..1171407c07a 100644
--- a/library/core/src/num/nonzero.rs
+++ b/library/core/src/num/nonzero.rs
@@ -20,7 +20,15 @@ use super::{IntErrorKind, ParseIntError};
 ///
 /// # Safety
 ///
-/// Types implementing this trait must be primitves that are valid when zeroed.
+/// Types implementing this trait must be primitives that are valid when zeroed.
+///
+/// The associated `Self::NonZeroInner` type must have the same size+align as `Self`,
+/// but with a niche and bit validity making it so the following `transmutes` are sound:
+///
+/// - `Self::NonZeroInner` to `Option<Self::NonZeroInner>`
+/// - `Option<Self::NonZeroInner>` to `Self`
+///
+/// (And, consequently, `Self::NonZeroInner` to `Self`.)
 #[unstable(
     feature = "nonzero_internals",
     reason = "implementation detail which may disappear or be replaced at any time",
@@ -434,17 +442,11 @@ where
         // of some not-inlined function, LLVM don't have range metadata
         // to understand that the value cannot be zero.
         //
-        // SAFETY: `Self` is guaranteed to have the same layout as `Option<Self>`.
-        match unsafe { intrinsics::transmute_unchecked(self) } {
-            None => {
-                // SAFETY: `NonZero` is guaranteed to only contain non-zero values, so this is unreachable.
-                unsafe { intrinsics::unreachable() }
-            }
-            Some(Self(inner)) => {
-                // SAFETY: `T::NonZeroInner` is guaranteed to have the same layout as `T`.
-                unsafe { intrinsics::transmute_unchecked(inner) }
-            }
-        }
+        // For now, using the transmute `assume`s the range at runtime.
+        //
+        // SAFETY: `ZeroablePrimitive` guarantees that the size and bit validity
+        // of `.0` is such that this transmute is sound.
+        unsafe { intrinsics::transmute_unchecked(self) }
     }
 }