diff options
| author | Jakub Beránek <berykubik@gmail.com> | 2025-01-20 15:54:51 +0100 |
|---|---|---|
| committer | GitHub <noreply@github.com> | 2025-01-20 15:54:51 +0100 |
| commit | 470ab13c5c28a42e706ee8cee92e44257065324f (patch) | |
| tree | ea612d81208c7fa15d3477ca173d9fe6a18ccc83 /library/core/src/ptr/alignment.rs | |
| parent | 1b5b0515f9c12ea8181deec0d9997fe9af6ab417 (diff) | |
| parent | 1e0204beae7c0ebc5cddc64d1375bc7ee95f41db (diff) | |
Merge pull request #2215 from Kobzol/pull
rustc pull
Diffstat (limited to 'library/core/src/ptr/alignment.rs')
| -rw-r--r-- | library/core/src/ptr/alignment.rs | 12 |
1 files changed, 9 insertions, 3 deletions
diff --git a/library/core/src/ptr/alignment.rs b/library/core/src/ptr/alignment.rs index 74a1d40f4e7..2da94e72566 100644 --- a/library/core/src/ptr/alignment.rs +++ b/library/core/src/ptr/alignment.rs @@ -42,9 +42,10 @@ impl Alignment { /// but in an `Alignment` instead of a `usize`. #[unstable(feature = "ptr_alignment_type", issue = "102070")] #[inline] + #[must_use] pub const fn of<T>() -> Self { - // SAFETY: rustc ensures that type alignment is always a power of two. - unsafe { Alignment::new_unchecked(mem::align_of::<T>()) } + // This can't actually panic since type alignment is always a power of two. + const { Alignment::new(mem::align_of::<T>()).unwrap() } } /// Creates an `Alignment` from a `usize`, or returns `None` if it's @@ -95,8 +96,13 @@ impl Alignment { #[unstable(feature = "ptr_alignment_type", issue = "102070")] #[inline] pub const fn as_nonzero(self) -> NonZero<usize> { + // This transmutes directly to avoid the UbCheck in `NonZero::new_unchecked` + // since there's no way for the user to trip that check anyway -- the + // validity invariant of the type would have to have been broken earlier -- + // and emitting it in an otherwise simple method is bad for compile time. + // SAFETY: All the discriminants are non-zero. - unsafe { NonZero::new_unchecked(self.as_usize()) } + unsafe { mem::transmute::<Alignment, NonZero<usize>>(self) } } /// Returns the base-2 logarithm of the alignment. |
