Skip to main content

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