core/alloc/
layout.rs

1// Seemingly inconsequential code changes to this file can lead to measurable
2// performance impact on compilation times, due at least in part to the fact
3// that the layout code gets called from many instantiations of the various
4// collections, resulting in having to optimize down excess IR multiple times.
5// Your performance intuition is useless. Run perf.
6
7#[cfg(not(feature = "ferrocene_certified"))]
8use crate::error::Error;
9#[cfg(not(feature = "ferrocene_certified"))]
10use crate::intrinsics::{unchecked_add, unchecked_mul, unchecked_sub};
11#[cfg(not(feature = "ferrocene_certified"))]
12use crate::mem::SizedTypeProperties;
13#[cfg(not(feature = "ferrocene_certified"))]
14use crate::ptr::{Alignment, NonNull};
15#[cfg(not(feature = "ferrocene_certified"))]
16use crate::{assert_unsafe_precondition, fmt, mem};
17#[cfg(feature = "ferrocene_certified")]
18use crate::{assert_unsafe_precondition, intrinsics::unchecked_sub, mem, ptr::Alignment};
19
20// While this function is used in one place and its implementation
21// could be inlined, the previous attempts to do so made rustc
22// slower:
23//
24// * https://github.com/rust-lang/rust/pull/72189
25// * https://github.com/rust-lang/rust/pull/79827
26const fn size_align<T>() -> (usize, usize) {
27    (size_of::<T>(), align_of::<T>())
28}
29
30/// Layout of a block of memory.
31///
32/// An instance of `Layout` describes a particular layout of memory.
33/// You build a `Layout` up as an input to give to an allocator.
34///
35/// All layouts have an associated size and a power-of-two alignment. The size, when rounded up to
36/// the nearest multiple of `align`, does not overflow `isize` (i.e., the rounded value will always be
37/// less than or equal to `isize::MAX`).
38///
39/// (Note that layouts are *not* required to have non-zero size,
40/// even though `GlobalAlloc` requires that all memory requests
41/// be non-zero in size. A caller must either ensure that conditions
42/// like this are met, use specific allocators with looser
43/// requirements, or use the more lenient `Allocator` interface.)
44#[stable(feature = "alloc_layout", since = "1.28.0")]
45#[cfg_attr(not(feature = "ferrocene_certified"), derive(Copy, Clone, Debug, PartialEq, Eq, Hash))]
46#[lang = "alloc_layout"]
47pub struct Layout {
48    // size of the requested block of memory, measured in bytes.
49    size: usize,
50
51    // alignment of the requested block of memory, measured in bytes.
52    // we ensure that this is always a power-of-two, because API's
53    // like `posix_memalign` require it and it is a reasonable
54    // constraint to impose on Layout constructors.
55    //
56    // (However, we do not analogously require `align >= sizeof(void*)`,
57    //  even though that is *also* a requirement of `posix_memalign`.)
58    align: Alignment,
59}
60
61impl Layout {
62    /// Constructs a `Layout` from a given `size` and `align`,
63    /// or returns `LayoutError` if any of the following conditions
64    /// are not met:
65    ///
66    /// * `align` must not be zero,
67    ///
68    /// * `align` must be a power of two,
69    ///
70    /// * `size`, when rounded up to the nearest multiple of `align`,
71    ///   must not overflow `isize` (i.e., the rounded value must be
72    ///   less than or equal to `isize::MAX`).
73    #[stable(feature = "alloc_layout", since = "1.28.0")]
74    #[rustc_const_stable(feature = "const_alloc_layout_size_align", since = "1.50.0")]
75    #[inline]
76    #[cfg(not(feature = "ferrocene_certified"))]
77    pub const fn from_size_align(size: usize, align: usize) -> Result<Self, LayoutError> {
78        if Layout::is_size_align_valid(size, align) {
79            // SAFETY: Layout::is_size_align_valid checks the preconditions for this call.
80            unsafe { Ok(Layout { size, align: mem::transmute(align) }) }
81        } else {
82            Err(LayoutError)
83        }
84    }
85
86    const fn is_size_align_valid(size: usize, align: usize) -> bool {
87        let Some(align) = Alignment::new(align) else { return false };
88        if size > Self::max_size_for_align(align) {
89            return false;
90        }
91        true
92    }
93
94    #[inline(always)]
95    const fn max_size_for_align(align: Alignment) -> usize {
96        // (power-of-two implies align != 0.)
97
98        // Rounded up size is:
99        //   size_rounded_up = (size + align - 1) & !(align - 1);
100        //
101        // We know from above that align != 0. If adding (align - 1)
102        // does not overflow, then rounding up will be fine.
103        //
104        // Conversely, &-masking with !(align - 1) will subtract off
105        // only low-order-bits. Thus if overflow occurs with the sum,
106        // the &-mask cannot subtract enough to undo that overflow.
107        //
108        // Above implies that checking for summation overflow is both
109        // necessary and sufficient.
110
111        // SAFETY: the maximum possible alignment is `isize::MAX + 1`,
112        // so the subtraction cannot overflow.
113        unsafe { unchecked_sub(isize::MAX as usize + 1, align.as_usize()) }
114    }
115
116    /// Internal helper constructor to skip revalidating alignment validity.
117    #[inline]
118    #[cfg(not(feature = "ferrocene_certified"))]
119    const fn from_size_alignment(size: usize, align: Alignment) -> Result<Self, LayoutError> {
120        if size > Self::max_size_for_align(align) {
121            return Err(LayoutError);
122        }
123
124        // SAFETY: Layout::size invariants checked above.
125        Ok(Layout { size, align })
126    }
127
128    /// Creates a layout, bypassing all checks.
129    ///
130    /// # Safety
131    ///
132    /// This function is unsafe as it does not verify the preconditions from
133    /// [`Layout::from_size_align`].
134    #[stable(feature = "alloc_layout", since = "1.28.0")]
135    #[rustc_const_stable(feature = "const_alloc_layout_unchecked", since = "1.36.0")]
136    #[must_use]
137    #[inline]
138    #[track_caller]
139    pub const unsafe fn from_size_align_unchecked(size: usize, align: usize) -> Self {
140        assert_unsafe_precondition!(
141            check_library_ub,
142            "Layout::from_size_align_unchecked requires that align is a power of 2 \
143            and the rounded-up allocation size does not exceed isize::MAX",
144            (
145                size: usize = size,
146                align: usize = align,
147            ) => Layout::is_size_align_valid(size, align)
148        );
149        // SAFETY: the caller is required to uphold the preconditions.
150        unsafe { Layout { size, align: mem::transmute(align) } }
151    }
152
153    /// The minimum size in bytes for a memory block of this layout.
154    #[stable(feature = "alloc_layout", since = "1.28.0")]
155    #[rustc_const_stable(feature = "const_alloc_layout_size_align", since = "1.50.0")]
156    #[must_use]
157    #[inline]
158    pub const fn size(&self) -> usize {
159        self.size
160    }
161
162    /// The minimum byte alignment for a memory block of this layout.
163    ///
164    /// The returned alignment is guaranteed to be a power of two.
165    #[stable(feature = "alloc_layout", since = "1.28.0")]
166    #[rustc_const_stable(feature = "const_alloc_layout_size_align", since = "1.50.0")]
167    #[must_use = "this returns the minimum alignment, \
168                  without modifying the layout"]
169    #[inline]
170    pub const fn align(&self) -> usize {
171        self.align.as_usize()
172    }
173
174    /// Constructs a `Layout` suitable for holding a value of type `T`.
175    #[stable(feature = "alloc_layout", since = "1.28.0")]
176    #[rustc_const_stable(feature = "alloc_layout_const_new", since = "1.42.0")]
177    #[must_use]
178    #[inline]
179    pub const fn new<T>() -> Self {
180        let (size, align) = size_align::<T>();
181        // SAFETY: if the type is instantiated, rustc already ensures that its
182        // layout is valid. Use the unchecked constructor to avoid inserting a
183        // panicking codepath that needs to be optimized out.
184        unsafe { Layout::from_size_align_unchecked(size, align) }
185    }
186
187    /// Produces layout describing a record that could be used to
188    /// allocate backing structure for `T` (which could be a trait
189    /// or other unsized type like a slice).
190    #[stable(feature = "alloc_layout", since = "1.28.0")]
191    #[rustc_const_stable(feature = "const_alloc_layout", since = "1.85.0")]
192    #[must_use]
193    #[inline]
194    #[cfg(not(feature = "ferrocene_certified"))]
195    pub const fn for_value<T: ?Sized>(t: &T) -> Self {
196        let (size, align) = (size_of_val(t), align_of_val(t));
197        // SAFETY: see rationale in `new` for why this is using the unsafe variant
198        unsafe { Layout::from_size_align_unchecked(size, align) }
199    }
200
201    /// Produces layout describing a record that could be used to
202    /// allocate backing structure for `T` (which could be a trait
203    /// or other unsized type like a slice).
204    ///
205    /// # Safety
206    ///
207    /// This function is only safe to call if the following conditions hold:
208    ///
209    /// - If `T` is `Sized`, this function is always safe to call.
210    /// - If the unsized tail of `T` is:
211    ///     - a [slice], then the length of the slice tail must be an initialized
212    ///       integer, and the size of the *entire value*
213    ///       (dynamic tail length + statically sized prefix) must fit in `isize`.
214    ///       For the special case where the dynamic tail length is 0, this function
215    ///       is safe to call.
216    ///     - a [trait object], then the vtable part of the pointer must point
217    ///       to a valid vtable for the type `T` acquired by an unsizing coercion,
218    ///       and the size of the *entire value*
219    ///       (dynamic tail length + statically sized prefix) must fit in `isize`.
220    ///     - an (unstable) [extern type], then this function is always safe to
221    ///       call, but may panic or otherwise return the wrong value, as the
222    ///       extern type's layout is not known. This is the same behavior as
223    ///       [`Layout::for_value`] on a reference to an extern type tail.
224    ///     - otherwise, it is conservatively not allowed to call this function.
225    ///
226    /// [trait object]: ../../book/ch17-02-trait-objects.html
227    /// [extern type]: ../../unstable-book/language-features/extern-types.html
228    #[unstable(feature = "layout_for_ptr", issue = "69835")]
229    #[must_use]
230    #[cfg(not(feature = "ferrocene_certified"))]
231    pub const unsafe fn for_value_raw<T: ?Sized>(t: *const T) -> Self {
232        // SAFETY: we pass along the prerequisites of these functions to the caller
233        let (size, align) = unsafe { (mem::size_of_val_raw(t), mem::align_of_val_raw(t)) };
234        // SAFETY: see rationale in `new` for why this is using the unsafe variant
235        unsafe { Layout::from_size_align_unchecked(size, align) }
236    }
237
238    /// Creates a `NonNull` that is dangling, but well-aligned for this Layout.
239    ///
240    /// Note that the pointer value may potentially represent a valid pointer,
241    /// which means this must not be used as a "not yet initialized"
242    /// sentinel value. Types that lazily allocate must track initialization by
243    /// some other means.
244    #[unstable(feature = "alloc_layout_extra", issue = "55724")]
245    #[must_use]
246    #[inline]
247    #[cfg(not(feature = "ferrocene_certified"))]
248    pub const fn dangling(&self) -> NonNull<u8> {
249        NonNull::without_provenance(self.align.as_nonzero())
250    }
251
252    /// Creates a layout describing the record that can hold a value
253    /// of the same layout as `self`, but that also is aligned to
254    /// alignment `align` (measured in bytes).
255    ///
256    /// If `self` already meets the prescribed alignment, then returns
257    /// `self`.
258    ///
259    /// Note that this method does not add any padding to the overall
260    /// size, regardless of whether the returned layout has a different
261    /// alignment. In other words, if `K` has size 16, `K.align_to(32)`
262    /// will *still* have size 16.
263    ///
264    /// Returns an error if the combination of `self.size()` and the given
265    /// `align` violates the conditions listed in [`Layout::from_size_align`].
266    #[stable(feature = "alloc_layout_manipulation", since = "1.44.0")]
267    #[rustc_const_stable(feature = "const_alloc_layout", since = "1.85.0")]
268    #[inline]
269    #[cfg(not(feature = "ferrocene_certified"))]
270    pub const fn align_to(&self, align: usize) -> Result<Self, LayoutError> {
271        if let Some(align) = Alignment::new(align) {
272            Layout::from_size_alignment(self.size, Alignment::max(self.align, align))
273        } else {
274            Err(LayoutError)
275        }
276    }
277
278    /// Returns the amount of padding we must insert after `self`
279    /// to ensure that the following address will satisfy `align`
280    /// (measured in bytes).
281    ///
282    /// e.g., if `self.size()` is 9, then `self.padding_needed_for(4)`
283    /// returns 3, because that is the minimum number of bytes of
284    /// padding required to get a 4-aligned address (assuming that the
285    /// corresponding memory block starts at a 4-aligned address).
286    ///
287    /// The return value of this function has no meaning if `align` is
288    /// not a power-of-two.
289    ///
290    /// Note that the utility of the returned value requires `align`
291    /// to be less than or equal to the alignment of the starting
292    /// address for the whole allocated block of memory. One way to
293    /// satisfy this constraint is to ensure `align <= self.align()`.
294    #[unstable(feature = "alloc_layout_extra", issue = "55724")]
295    #[must_use = "this returns the padding needed, \
296                  without modifying the `Layout`"]
297    #[inline]
298    #[cfg(not(feature = "ferrocene_certified"))]
299    pub const fn padding_needed_for(&self, align: usize) -> usize {
300        // FIXME: Can we just change the type on this to `Alignment`?
301        let Some(align) = Alignment::new(align) else { return usize::MAX };
302        let len_rounded_up = self.size_rounded_up_to_custom_align(align);
303        // SAFETY: Cannot overflow because the rounded-up value is never less
304        unsafe { unchecked_sub(len_rounded_up, self.size) }
305    }
306
307    /// Returns the smallest multiple of `align` greater than or equal to `self.size()`.
308    ///
309    /// This can return at most `Alignment::MAX` (aka `isize::MAX + 1`)
310    /// because the original size is at most `isize::MAX`.
311    #[inline]
312    #[cfg(not(feature = "ferrocene_certified"))]
313    const fn size_rounded_up_to_custom_align(&self, align: Alignment) -> usize {
314        // SAFETY:
315        // Rounded up value is:
316        //   size_rounded_up = (size + align - 1) & !(align - 1);
317        //
318        // The arithmetic we do here can never overflow:
319        //
320        // 1. align is guaranteed to be > 0, so align - 1 is always
321        //    valid.
322        //
323        // 2. size is at most `isize::MAX`, so adding `align - 1` (which is at
324        //    most `isize::MAX`) can never overflow a `usize`.
325        //
326        // 3. masking by the alignment can remove at most `align - 1`,
327        //    which is what we just added, thus the value we return is never
328        //    less than the original `size`.
329        //
330        // (Size 0 Align MAX is already aligned, so stays the same, but things like
331        // Size 1 Align MAX or Size isize::MAX Align 2 round up to `isize::MAX + 1`.)
332        unsafe {
333            let align_m1 = unchecked_sub(align.as_usize(), 1);
334            let size_rounded_up = unchecked_add(self.size, align_m1) & !align_m1;
335            size_rounded_up
336        }
337    }
338
339    /// Creates a layout by rounding the size of this layout up to a multiple
340    /// of the layout's alignment.
341    ///
342    /// This is equivalent to adding the result of `padding_needed_for`
343    /// to the layout's current size.
344    #[stable(feature = "alloc_layout_manipulation", since = "1.44.0")]
345    #[rustc_const_stable(feature = "const_alloc_layout", since = "1.85.0")]
346    #[must_use = "this returns a new `Layout`, \
347                  without modifying the original"]
348    #[inline]
349    #[cfg(not(feature = "ferrocene_certified"))]
350    pub const fn pad_to_align(&self) -> Layout {
351        // This cannot overflow. Quoting from the invariant of Layout:
352        // > `size`, when rounded up to the nearest multiple of `align`,
353        // > must not overflow isize (i.e., the rounded value must be
354        // > less than or equal to `isize::MAX`)
355        let new_size = self.size_rounded_up_to_custom_align(self.align);
356
357        // SAFETY: padded size is guaranteed to not exceed `isize::MAX`.
358        unsafe { Layout::from_size_align_unchecked(new_size, self.align()) }
359    }
360
361    /// Creates a layout describing the record for `n` instances of
362    /// `self`, with a suitable amount of padding between each to
363    /// ensure that each instance is given its requested size and
364    /// alignment. On success, returns `(k, offs)` where `k` is the
365    /// layout of the array and `offs` is the distance between the start
366    /// of each element in the array.
367    ///
368    /// (That distance between elements is sometimes known as "stride".)
369    ///
370    /// On arithmetic overflow, returns `LayoutError`.
371    ///
372    /// # Examples
373    ///
374    /// ```
375    /// #![feature(alloc_layout_extra)]
376    /// use std::alloc::Layout;
377    ///
378    /// // All rust types have a size that's a multiple of their alignment.
379    /// let normal = Layout::from_size_align(12, 4).unwrap();
380    /// let repeated = normal.repeat(3).unwrap();
381    /// assert_eq!(repeated, (Layout::from_size_align(36, 4).unwrap(), 12));
382    ///
383    /// // But you can manually make layouts which don't meet that rule.
384    /// let padding_needed = Layout::from_size_align(6, 4).unwrap();
385    /// let repeated = padding_needed.repeat(3).unwrap();
386    /// assert_eq!(repeated, (Layout::from_size_align(24, 4).unwrap(), 8));
387    /// ```
388    #[unstable(feature = "alloc_layout_extra", issue = "55724")]
389    #[inline]
390    #[cfg(not(feature = "ferrocene_certified"))]
391    pub const fn repeat(&self, n: usize) -> Result<(Self, usize), LayoutError> {
392        let padded = self.pad_to_align();
393        if let Ok(repeated) = padded.repeat_packed(n) {
394            Ok((repeated, padded.size()))
395        } else {
396            Err(LayoutError)
397        }
398    }
399
400    /// Creates a layout describing the record for `self` followed by
401    /// `next`, including any necessary padding to ensure that `next`
402    /// will be properly aligned, but *no trailing padding*.
403    ///
404    /// In order to match C representation layout `repr(C)`, you should
405    /// call `pad_to_align` after extending the layout with all fields.
406    /// (There is no way to match the default Rust representation
407    /// layout `repr(Rust)`, as it is unspecified.)
408    ///
409    /// Note that the alignment of the resulting layout will be the maximum of
410    /// those of `self` and `next`, in order to ensure alignment of both parts.
411    ///
412    /// Returns `Ok((k, offset))`, where `k` is layout of the concatenated
413    /// record and `offset` is the relative location, in bytes, of the
414    /// start of the `next` embedded within the concatenated record
415    /// (assuming that the record itself starts at offset 0).
416    ///
417    /// On arithmetic overflow, returns `LayoutError`.
418    ///
419    /// # Examples
420    ///
421    /// To calculate the layout of a `#[repr(C)]` structure and the offsets of
422    /// the fields from its fields' layouts:
423    ///
424    /// ```rust
425    /// # use std::alloc::{Layout, LayoutError};
426    /// pub fn repr_c(fields: &[Layout]) -> Result<(Layout, Vec<usize>), LayoutError> {
427    ///     let mut offsets = Vec::new();
428    ///     let mut layout = Layout::from_size_align(0, 1)?;
429    ///     for &field in fields {
430    ///         let (new_layout, offset) = layout.extend(field)?;
431    ///         layout = new_layout;
432    ///         offsets.push(offset);
433    ///     }
434    ///     // Remember to finalize with `pad_to_align`!
435    ///     Ok((layout.pad_to_align(), offsets))
436    /// }
437    /// # // test that it works
438    /// # #[repr(C)] struct S { a: u64, b: u32, c: u16, d: u32 }
439    /// # let s = Layout::new::<S>();
440    /// # let u16 = Layout::new::<u16>();
441    /// # let u32 = Layout::new::<u32>();
442    /// # let u64 = Layout::new::<u64>();
443    /// # assert_eq!(repr_c(&[u64, u32, u16, u32]), Ok((s, vec![0, 8, 12, 16])));
444    /// ```
445    #[stable(feature = "alloc_layout_manipulation", since = "1.44.0")]
446    #[rustc_const_stable(feature = "const_alloc_layout", since = "1.85.0")]
447    #[inline]
448    #[cfg(not(feature = "ferrocene_certified"))]
449    pub const fn extend(&self, next: Self) -> Result<(Self, usize), LayoutError> {
450        let new_align = Alignment::max(self.align, next.align);
451        let offset = self.size_rounded_up_to_custom_align(next.align);
452
453        // SAFETY: `offset` is at most `isize::MAX + 1` (such as from aligning
454        // to `Alignment::MAX`) and `next.size` is at most `isize::MAX` (from the
455        // `Layout` type invariant).  Thus the largest possible `new_size` is
456        // `isize::MAX + 1 + isize::MAX`, which is `usize::MAX`, and cannot overflow.
457        let new_size = unsafe { unchecked_add(offset, next.size) };
458
459        if let Ok(layout) = Layout::from_size_alignment(new_size, new_align) {
460            Ok((layout, offset))
461        } else {
462            Err(LayoutError)
463        }
464    }
465
466    /// Creates a layout describing the record for `n` instances of
467    /// `self`, with no padding between each instance.
468    ///
469    /// Note that, unlike `repeat`, `repeat_packed` does not guarantee
470    /// that the repeated instances of `self` will be properly
471    /// aligned, even if a given instance of `self` is properly
472    /// aligned. In other words, if the layout returned by
473    /// `repeat_packed` is used to allocate an array, it is not
474    /// guaranteed that all elements in the array will be properly
475    /// aligned.
476    ///
477    /// On arithmetic overflow, returns `LayoutError`.
478    #[unstable(feature = "alloc_layout_extra", issue = "55724")]
479    #[inline]
480    #[cfg(not(feature = "ferrocene_certified"))]
481    pub const fn repeat_packed(&self, n: usize) -> Result<Self, LayoutError> {
482        if let Some(size) = self.size.checked_mul(n) {
483            // The safe constructor is called here to enforce the isize size limit.
484            Layout::from_size_alignment(size, self.align)
485        } else {
486            Err(LayoutError)
487        }
488    }
489
490    /// Creates a layout describing the record for `self` followed by
491    /// `next` with no additional padding between the two. Since no
492    /// padding is inserted, the alignment of `next` is irrelevant,
493    /// and is not incorporated *at all* into the resulting layout.
494    ///
495    /// On arithmetic overflow, returns `LayoutError`.
496    #[unstable(feature = "alloc_layout_extra", issue = "55724")]
497    #[inline]
498    #[cfg(not(feature = "ferrocene_certified"))]
499    pub const fn extend_packed(&self, next: Self) -> Result<Self, LayoutError> {
500        // SAFETY: each `size` is at most `isize::MAX == usize::MAX/2`, so the
501        // sum is at most `usize::MAX/2*2 == usize::MAX - 1`, and cannot overflow.
502        let new_size = unsafe { unchecked_add(self.size, next.size) };
503        // The safe constructor enforces that the new size isn't too big for the alignment
504        Layout::from_size_alignment(new_size, self.align)
505    }
506
507    /// Creates a layout describing the record for a `[T; n]`.
508    ///
509    /// On arithmetic overflow or when the total size would exceed
510    /// `isize::MAX`, returns `LayoutError`.
511    #[stable(feature = "alloc_layout_manipulation", since = "1.44.0")]
512    #[rustc_const_stable(feature = "const_alloc_layout", since = "1.85.0")]
513    #[inline]
514    #[cfg(not(feature = "ferrocene_certified"))]
515    pub const fn array<T>(n: usize) -> Result<Self, LayoutError> {
516        // Reduce the amount of code we need to monomorphize per `T`.
517        return inner(T::LAYOUT, n);
518
519        #[inline]
520        const fn inner(element_layout: Layout, n: usize) -> Result<Layout, LayoutError> {
521            let Layout { size: element_size, align } = element_layout;
522
523            // We need to check two things about the size:
524            //  - That the total size won't overflow a `usize`, and
525            //  - That the total size still fits in an `isize`.
526            // By using division we can check them both with a single threshold.
527            // That'd usually be a bad idea, but thankfully here the element size
528            // and alignment are constants, so the compiler will fold all of it.
529            if element_size != 0 && n > Layout::max_size_for_align(align) / element_size {
530                return Err(LayoutError);
531            }
532
533            // SAFETY: We just checked that we won't overflow `usize` when we multiply.
534            // This is a useless hint inside this function, but after inlining this helps
535            // deduplicate checks for whether the overall capacity is zero (e.g., in RawVec's
536            // allocation path) before/after this multiplication.
537            let array_size = unsafe { unchecked_mul(element_size, n) };
538
539            // SAFETY: We just checked above that the `array_size` will not
540            // exceed `isize::MAX` even when rounded up to the alignment.
541            // And `Alignment` guarantees it's a power of two.
542            unsafe { Ok(Layout::from_size_align_unchecked(array_size, align.as_usize())) }
543        }
544    }
545
546    /// Perma-unstable access to `align` as `Alignment` type.
547    #[unstable(issue = "none", feature = "std_internals")]
548    #[doc(hidden)]
549    #[inline]
550    #[cfg(not(feature = "ferrocene_certified"))]
551    pub const fn alignment(&self) -> Alignment {
552        self.align
553    }
554}
555
556#[stable(feature = "alloc_layout", since = "1.28.0")]
557#[deprecated(
558    since = "1.52.0",
559    note = "Name does not follow std convention, use LayoutError",
560    suggestion = "LayoutError"
561)]
562#[cfg(not(feature = "ferrocene_certified"))]
563pub type LayoutErr = LayoutError;
564
565/// The `LayoutError` is returned when the parameters given
566/// to `Layout::from_size_align`
567/// or some other `Layout` constructor
568/// do not satisfy its documented constraints.
569#[stable(feature = "alloc_layout_error", since = "1.50.0")]
570#[non_exhaustive]
571#[derive(Clone, PartialEq, Eq, Debug)]
572#[cfg(not(feature = "ferrocene_certified"))]
573pub struct LayoutError;
574
575#[stable(feature = "alloc_layout", since = "1.28.0")]
576#[cfg(not(feature = "ferrocene_certified"))]
577impl Error for LayoutError {}
578
579// (we need this for downstream impl of trait Error)
580#[stable(feature = "alloc_layout", since = "1.28.0")]
581#[cfg(not(feature = "ferrocene_certified"))]
582impl fmt::Display for LayoutError {
583    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
584        f.write_str("invalid parameters to Layout::from_size_align")
585    }
586}