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