diff --git a/library/alloc/src/lib.rs b/library/alloc/src/lib.rs index 895d1b8d59f2c..c122e14854f57 100644 --- a/library/alloc/src/lib.rs +++ b/library/alloc/src/lib.rs @@ -138,6 +138,7 @@ #![feature(maybe_uninit_uninit_array_transpose)] #![feature(panic_internals)] #![feature(pattern)] +#![feature(ptr_alignment_type)] #![feature(ptr_internals)] #![feature(ptr_metadata)] #![feature(ptr_sub_ptr)] diff --git a/library/alloc/src/raw_vec.rs b/library/alloc/src/raw_vec.rs index 1134c7f833e2b..569aac75d2aef 100644 --- a/library/alloc/src/raw_vec.rs +++ b/library/alloc/src/raw_vec.rs @@ -4,7 +4,7 @@ use core::alloc::LayoutError; use core::cmp; use core::hint; use core::mem::{self, ManuallyDrop, MaybeUninit, SizedTypeProperties}; -use core::ptr::{self, NonNull, Unique}; +use core::ptr::{self, Alignment, NonNull, Unique}; #[cfg(not(no_global_oom_handling))] use crate::alloc::handle_alloc_error; @@ -306,9 +306,9 @@ impl RawVec { // support such types. So we can do better by skipping some checks and avoid an unwrap. const { assert!(mem::size_of::() % mem::align_of::() == 0) }; unsafe { - let align = mem::align_of::(); + let align = Alignment::of::(); let size = mem::size_of::().unchecked_mul(self.cap.0); - let layout = Layout::from_size_align_unchecked(size, align); + let layout = Layout::from_size_alignment(size, align).unwrap_unchecked(); Some((self.ptr.cast().into(), layout)) } } diff --git a/library/core/src/alloc/layout.rs b/library/core/src/alloc/layout.rs index 0b92767c93205..b577c531ff55c 100644 --- a/library/core/src/alloc/layout.rs +++ b/library/core/src/alloc/layout.rs @@ -4,6 +4,7 @@ // collections, resulting in having to optimize down excess IR multiple times. // Your performance intuition is useless. Run perf. +use crate::assert_unsafe_precondition; use crate::cmp; use crate::error::Error; use crate::fmt; @@ -96,8 +97,10 @@ impl Layout { } /// Internal helper constructor to skip revalidating alignment validity. + #[unstable(feature = "ptr_alignment_type", issue = "102070")] + #[rustc_const_unstable(feature = "ptr_alignment_type", issue = "102070")] #[inline] - const fn from_size_alignment(size: usize, align: Alignment) -> Result { + pub const fn from_size_alignment(size: usize, align: Alignment) -> Result { if size > Self::max_size_for_align(align) { return Err(LayoutError); } @@ -118,6 +121,15 @@ impl Layout { #[inline] #[rustc_allow_const_fn_unstable(ptr_alignment_type)] pub const unsafe fn from_size_align_unchecked(size: usize, align: usize) -> Self { + assert_unsafe_precondition!( + check_library_ub, + "Layout::from_size_align_unchecked requires that align is a power of 2 \ + and the rounded-up allocation size does not exceed isize::MAX", + ( + size: usize = size, + align: usize = align, + ) => Layout::from_size_align(size, align).is_ok() + ); // SAFETY: the caller is required to uphold the preconditions. unsafe { Layout { size, align: Alignment::new_unchecked(align) } } }