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] `[U]`, `str`, or a [trait object] `dyn Trait`, then the size of the *entire value*
236 /// (dynamic tail length + statically sized prefix) must fit in `isize`.
237 /// For the special case where the dynamic tail length is 0, this function
238 /// is safe to call.
239 // NOTE: the reason this is safe is that if an overflow were to occur already with size 0,
240 // then we would stop compilation as even the "statically known" part of the type would
241 // already be too big (or the call may be in dead code and optimized away, but then it
242 // doesn't matter).
243 /// - No other kind of unsized tail currently exists that satisfies the trait bounds for this
244 /// function. If more kinds of unsized tails get introduced in the future, the documentation
245 /// of this function will have to be extended before it can be used for such types.
246 ///
247 /// Here, *unsized tail* refers to the type obtained by recursively descending through the last
248 /// field of a tuple or struct until we arrived at a built-in unsized type.
249 ///
250 /// As a consequence of these rules, it is the case that whenever it is allowed to convert `val`
251 /// into a shared reference, then it is also allowed to invoke this function.
252 ///
253 /// [trait object]: ../../book/ch17-02-trait-objects.html
254 /// [extern type]: ../../unstable-book/language-features/extern-types.html
255 #[stable(feature = "layout_for_ptr", since = "CURRENT_RUSTC_VERSION")]
256 #[rustc_const_stable(feature = "layout_for_ptr", since = "CURRENT_RUSTC_VERSION")]
257 #[must_use]
258 #[inline]
259 pub const unsafe fn for_value_raw<T: ?Sized>(val: *const T) -> Self {
260 // SAFETY: we pass along the prerequisites of these functions to the caller
261 let (size, alignment) = unsafe { (mem::size_of_val_raw(val), Alignment::of_val_raw(val)) };
262 // SAFETY: see rationale in `new` for why this is using the unsafe variant
263 unsafe { Layout::from_size_alignment_unchecked(size, alignment) }
264 }
265
266 /// Creates a `NonNull` that is dangling, but well-aligned for this Layout.
267 ///
268 /// Note that the address of the returned pointer may potentially
269 /// be that of a valid pointer, which means this must not be used
270 /// as a "not yet initialized" sentinel value.
271 /// Types that lazily allocate must track initialization by some other means.
272 #[stable(feature = "alloc_layout_extra", since = "1.95.0")]
273 #[rustc_const_stable(feature = "alloc_layout_extra", since = "1.95.0")]
274 #[must_use]
275 #[inline]
276 pub const fn dangling_ptr(&self) -> NonNull<u8> {
277 NonNull::without_provenance(self.align.as_nonzero_usize())
278 }
279
280 /// Creates a layout describing the record that can hold a value
281 /// of the same layout as `self`, but that also is aligned to
282 /// alignment `align` (measured in bytes).
283 ///
284 /// If `self` already meets the prescribed alignment, then returns
285 /// `self`.
286 ///
287 /// Note that this method does not add any padding to the overall
288 /// size, regardless of whether the returned layout has a different
289 /// alignment. In other words, if `K` has size 16, `K.align_to(32)`
290 /// will *still* have size 16.
291 ///
292 /// Returns an error if the combination of `self.size()` and the given
293 /// `align` violates the conditions listed in [`Layout::from_size_align`].
294 #[stable(feature = "alloc_layout_manipulation", since = "1.44.0")]
295 #[rustc_const_stable(feature = "const_alloc_layout", since = "1.85.0")]
296 #[inline]
297 pub const fn align_to(&self, align: usize) -> Result<Self, LayoutError> {
298 if let Some(alignment) = Alignment::new(align) {
299 self.adjust_alignment_to(alignment)
300 } else {
301 Err(LayoutError)
302 }
303 }
304
305 /// Creates a layout describing the record that can hold a value
306 /// of the same layout as `self`, but that also is aligned to
307 /// alignment `alignment`.
308 ///
309 /// If `self` already meets the prescribed alignment, then returns
310 /// `self`.
311 ///
312 /// Note that this method does not add any padding to the overall
313 /// size, regardless of whether the returned layout has a different
314 /// alignment. In other words, if `K` has size 16, `K.align_to(32)`
315 /// will *still* have size 16.
316 ///
317 /// Returns an error if the combination of `self.size()` and the given
318 /// `alignment` violates the conditions listed in [`Layout::from_size_alignment`].
319 #[unstable(feature = "ptr_alignment_type", issue = "102070")]
320 #[inline]
321 pub const fn adjust_alignment_to(&self, alignment: Alignment) -> Result<Self, LayoutError> {
322 Layout::from_size_alignment(self.size, Alignment::max(self.align, alignment))
323 }
324
325 /// Returns the amount of padding we must insert after `self`
326 /// to ensure that the following address will satisfy `alignment`.
327 ///
328 /// e.g., if `self.size()` is 9, then `self.padding_needed_for(alignment4)`
329 /// (where `alignment4.as_usize() == 4`)
330 /// returns 3, because that is the minimum number of bytes of
331 /// padding required to get a 4-aligned address (assuming that the
332 /// corresponding memory block starts at a 4-aligned address).
333 ///
334 /// Note that the utility of the returned value requires `alignment`
335 /// to be less than or equal to the alignment of the starting
336 /// address for the whole allocated block of memory. One way to
337 /// satisfy this constraint is to ensure `alignment.as_usize() <= self.align()`.
338 #[unstable(feature = "ptr_alignment_type", issue = "102070")]
339 #[must_use = "this returns the padding needed, without modifying the `Layout`"]
340 #[inline]
341 pub const fn padding_needed_for(&self, alignment: Alignment) -> usize {
342 let len_rounded_up = self.size_rounded_up_to_custom_alignment(alignment);
343 // SAFETY: Cannot overflow because the rounded-up value is never less
344 unsafe { unchecked_sub(len_rounded_up, self.size) }
345 }
346
347 /// Returns the smallest multiple of `align` greater than or equal to `self.size()`.
348 ///
349 /// This can return at most `Alignment::MAX` (aka `isize::MAX + 1`)
350 /// because the original size is at most `isize::MAX`.
351 #[inline]
352 const fn size_rounded_up_to_custom_alignment(&self, alignment: Alignment) -> usize {
353 // SAFETY:
354 // Rounded up value is:
355 // size_rounded_up = (size + align - 1) & !(align - 1);
356 //
357 // The arithmetic we do here can never overflow:
358 //
359 // 1. align is guaranteed to be > 0, so align - 1 is always
360 // valid.
361 //
362 // 2. size is at most `isize::MAX`, so adding `align - 1` (which is at
363 // most `isize::MAX`) can never overflow a `usize`.
364 //
365 // 3. masking by the alignment can remove at most `align - 1`,
366 // which is what we just added, thus the value we return is never
367 // less than the original `size`.
368 //
369 // (Size 0 Align MAX is already aligned, so stays the same, but things like
370 // Size 1 Align MAX or Size isize::MAX Align 2 round up to `isize::MAX + 1`.)
371 unsafe {
372 let align_m1 = unchecked_sub(alignment.as_usize(), 1);
373 unchecked_add(self.size, align_m1) & !align_m1
374 }
375 }
376
377 /// Creates a layout by rounding the size of this layout up to a multiple
378 /// of the layout's alignment.
379 ///
380 /// This is equivalent to adding the result of `padding_needed_for`
381 /// to the layout's current size.
382 #[stable(feature = "alloc_layout_manipulation", since = "1.44.0")]
383 #[rustc_const_stable(feature = "const_alloc_layout", since = "1.85.0")]
384 #[must_use = "this returns a new `Layout`, \
385 without modifying the original"]
386 #[inline]
387 pub const fn pad_to_align(&self) -> Layout {
388 // This cannot overflow. Quoting from the invariant of Layout:
389 // > `size`, when rounded up to the nearest multiple of `align`,
390 // > must not overflow isize (i.e., the rounded value must be
391 // > less than or equal to `isize::MAX`)
392 let new_size = self.size_rounded_up_to_custom_alignment(self.align);
393
394 // SAFETY: padded size is guaranteed to not exceed `isize::MAX`.
395 unsafe { Layout::from_size_alignment_unchecked(new_size, self.alignment()) }
396 }
397
398 /// Creates a layout describing the record for `n` instances of
399 /// `self`, with a suitable amount of padding between each to
400 /// ensure that each instance is given its requested size and
401 /// alignment. On success, returns `(k, offs)` where `k` is the
402 /// layout of the array and `offs` is the distance between the start
403 /// of each element in the array.
404 ///
405 /// Does not include padding after the trailing element.
406 ///
407 /// (That distance between elements is sometimes known as "stride".)
408 ///
409 /// On arithmetic overflow, returns `LayoutError`.
410 ///
411 /// # Examples
412 ///
413 /// ```
414 /// use std::alloc::Layout;
415 ///
416 /// // All rust types have a size that's a multiple of their alignment.
417 /// let normal = Layout::from_size_align(12, 4).unwrap();
418 /// let repeated = normal.repeat(3).unwrap();
419 /// assert_eq!(repeated, (Layout::from_size_align(36, 4).unwrap(), 12));
420 ///
421 /// // But you can manually make layouts which don't meet that rule.
422 /// let padding_needed = Layout::from_size_align(6, 4).unwrap();
423 /// let repeated = padding_needed.repeat(3).unwrap();
424 /// assert_eq!(repeated, (Layout::from_size_align(22, 4).unwrap(), 8));
425 ///
426 /// // Repeating an element zero times has zero size, but keeps the alignment (like `[T; 0]`)
427 /// let repeated = normal.repeat(0).unwrap();
428 /// assert_eq!(repeated, (Layout::from_size_align(0, 4).unwrap(), 12));
429 /// let repeated = padding_needed.repeat(0).unwrap();
430 /// assert_eq!(repeated, (Layout::from_size_align(0, 4).unwrap(), 8));
431 /// ```
432 #[stable(feature = "alloc_layout_extra", since = "1.95.0")]
433 #[rustc_const_stable(feature = "alloc_layout_extra", since = "1.95.0")]
434 #[inline]
435 pub const fn repeat(&self, n: usize) -> Result<(Self, usize), LayoutError> {
436 // FIXME(const-hack): the following could be way shorter with `?`
437 let padded = self.pad_to_align();
438 let Ok(result) = (if let Some(k) = n.checked_sub(1) {
439 let Ok(repeated) = padded.repeat_packed(k) else {
440 return Err(LayoutError);
441 };
442 repeated.extend_packed(*self)
443 } else {
444 debug_assert!(n == 0);
445 self.repeat_packed(0)
446 }) else {
447 return Err(LayoutError);
448 };
449 Ok((result, padded.size()))
450 }
451
452 /// Creates a layout describing the record for `self` followed by
453 /// `next`, including any necessary padding to ensure that `next`
454 /// will be properly aligned, but *no trailing padding*.
455 ///
456 /// In order to match C representation layout `repr(C)`, you should
457 /// call `pad_to_align` after extending the layout with all fields.
458 /// (There is no way to match the default Rust representation
459 /// layout `repr(Rust)`, as it is unspecified.)
460 ///
461 /// Note that the alignment of the resulting layout will be the maximum of
462 /// those of `self` and `next`, in order to ensure alignment of both parts.
463 ///
464 /// Returns `Ok((k, offset))`, where `k` is layout of the concatenated
465 /// record and `offset` is the relative location, in bytes, of the
466 /// start of the `next` embedded within the concatenated record
467 /// (assuming that the record itself starts at offset 0).
468 ///
469 /// On arithmetic overflow, returns `LayoutError`.
470 ///
471 /// # Examples
472 ///
473 /// To calculate the layout of a `#[repr(C)]` structure and the offsets of
474 /// the fields from its fields' layouts:
475 ///
476 /// ```rust
477 /// # use std::alloc::{Layout, LayoutError};
478 /// pub fn repr_c(fields: &[Layout]) -> Result<(Layout, Vec<usize>), LayoutError> {
479 /// let mut offsets = Vec::new();
480 /// let mut layout = Layout::from_size_align(0, 1)?;
481 /// for &field in fields {
482 /// let (new_layout, offset) = layout.extend(field)?;
483 /// layout = new_layout;
484 /// offsets.push(offset);
485 /// }
486 /// // Remember to finalize with `pad_to_align`!
487 /// Ok((layout.pad_to_align(), offsets))
488 /// }
489 /// # // test that it works
490 /// # #[repr(C)] struct S { a: u64, b: u32, c: u16, d: u32 }
491 /// # let s = Layout::new::<S>();
492 /// # let u16 = Layout::new::<u16>();
493 /// # let u32 = Layout::new::<u32>();
494 /// # let u64 = Layout::new::<u64>();
495 /// # assert_eq!(repr_c(&[u64, u32, u16, u32]), Ok((s, vec![0, 8, 12, 16])));
496 /// ```
497 #[stable(feature = "alloc_layout_manipulation", since = "1.44.0")]
498 #[rustc_const_stable(feature = "const_alloc_layout", since = "1.85.0")]
499 #[inline]
500 pub const fn extend(&self, next: Self) -> Result<(Self, usize), LayoutError> {
501 let new_alignment = Alignment::max(self.align, next.align);
502 let offset = self.size_rounded_up_to_custom_alignment(next.align);
503
504 // SAFETY: `offset` is at most `isize::MAX + 1` (such as from aligning
505 // to `Alignment::MAX`) and `next.size` is at most `isize::MAX` (from the
506 // `Layout` type invariant). Thus the largest possible `new_size` is
507 // `isize::MAX + 1 + isize::MAX`, which is `usize::MAX`, and cannot overflow.
508 let new_size = unsafe { unchecked_add(offset, next.size) };
509
510 if let Ok(layout) = Layout::from_size_alignment(new_size, new_alignment) {
511 Ok((layout, offset))
512 } else {
513 Err(LayoutError)
514 }
515 }
516
517 /// Creates a layout describing the record for `n` instances of
518 /// `self`, with no padding between each instance.
519 ///
520 /// Note that, unlike `repeat`, `repeat_packed` does not guarantee
521 /// that the repeated instances of `self` will be properly
522 /// aligned, even if a given instance of `self` is properly
523 /// aligned. In other words, if the layout returned by
524 /// `repeat_packed` is used to allocate an array, it is not
525 /// guaranteed that all elements in the array will be properly
526 /// aligned.
527 ///
528 /// On arithmetic overflow, returns `LayoutError`.
529 #[stable(feature = "alloc_layout_extra", since = "1.95.0")]
530 #[rustc_const_stable(feature = "alloc_layout_extra", since = "1.95.0")]
531 #[inline]
532 pub const fn repeat_packed(&self, n: usize) -> Result<Self, LayoutError> {
533 if let Some(size) = self.size.checked_mul(n) {
534 // The safe constructor is called here to enforce the isize size limit.
535 Layout::from_size_alignment(size, self.align)
536 } else {
537 Err(LayoutError)
538 }
539 }
540
541 /// Creates a layout describing the record for `self` followed by
542 /// `next` with no additional padding between the two. Since no
543 /// padding is inserted, the alignment of `next` is irrelevant,
544 /// and is not incorporated *at all* into the resulting layout.
545 ///
546 /// On arithmetic overflow, returns `LayoutError`.
547 #[stable(feature = "alloc_layout_extra", since = "1.95.0")]
548 #[rustc_const_stable(feature = "alloc_layout_extra", since = "1.95.0")]
549 #[inline]
550 pub const fn extend_packed(&self, next: Self) -> Result<Self, LayoutError> {
551 // SAFETY: each `size` is at most `isize::MAX == usize::MAX/2`, so the
552 // sum is at most `usize::MAX/2*2 == usize::MAX - 1`, and cannot overflow.
553 let new_size = unsafe { unchecked_add(self.size, next.size) };
554 // The safe constructor enforces that the new size isn't too big for the alignment
555 Layout::from_size_alignment(new_size, self.align)
556 }
557
558 /// Creates a layout describing the record for a `[T; n]`.
559 ///
560 /// On arithmetic overflow or when the total size would exceed
561 /// `isize::MAX`, returns `LayoutError`.
562 #[stable(feature = "alloc_layout_manipulation", since = "1.44.0")]
563 #[rustc_const_stable(feature = "const_alloc_layout", since = "1.85.0")]
564 #[inline]
565 pub const fn array<T>(n: usize) -> Result<Self, LayoutError> {
566 // Reduce the amount of code we need to monomorphize per `T`.
567 return inner(T::LAYOUT, n);
568
569 #[inline]
570 const fn inner(element_layout: Layout, n: usize) -> Result<Layout, LayoutError> {
571 let Layout { size: element_size, align: alignment } = element_layout;
572
573 // We need to check two things about the size:
574 // - That the total size won't overflow a `usize`, and
575 // - That the total size still fits in an `isize`.
576 // By using division we can check them both with a single threshold.
577 // That'd usually be a bad idea, but thankfully here the element size
578 // and alignment are constants, so the compiler will fold all of it.
579 if element_size != 0 && n > Layout::max_size_for_alignment(alignment) / element_size {
580 return Err(LayoutError);
581 }
582
583 // SAFETY: We just checked that we won't overflow `usize` when we multiply.
584 // This is a useless hint inside this function, but after inlining this helps
585 // deduplicate checks for whether the overall capacity is zero (e.g., in RawVec's
586 // allocation path) before/after this multiplication.
587 let array_size = unsafe { unchecked_mul(element_size, n) };
588
589 // SAFETY: We just checked above that the `array_size` will not
590 // exceed `isize::MAX` even when rounded up to the alignment.
591 // And `Alignment` guarantees it's a power of two.
592 unsafe { Ok(Layout::from_size_alignment_unchecked(array_size, alignment)) }
593 }
594 }
595}
596
597#[stable(feature = "alloc_layout", since = "1.28.0")]
598#[deprecated(
599 since = "1.52.0",
600 note = "Name does not follow std convention, use LayoutError",
601 suggestion = "LayoutError"
602)]
603pub type LayoutErr = LayoutError;
604
605/// The `LayoutError` is returned when the parameters given
606/// to `Layout::from_size_align`
607/// or some other `Layout` constructor
608/// do not satisfy its documented constraints.
609#[stable(feature = "alloc_layout_error", since = "1.50.0")]
610#[non_exhaustive]
611#[derive(Clone, PartialEq, Eq, Debug)]
612pub struct LayoutError;
613
614#[stable(feature = "alloc_layout", since = "1.28.0")]
615impl Error for LayoutError {}
616
617// (we need this for downstream impl of trait Error)
618#[stable(feature = "alloc_layout", since = "1.28.0")]
619impl fmt::Display for LayoutError {
620 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
621 f.write_str("invalid parameters to Layout::from_size_align")
622 }
623}