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