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