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