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