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