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