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