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