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