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.
9 use crate::error::Error;
11 use crate::mem::{self, ValidAlign};
12 use crate::ptr::NonNull;
14 // While this function is used in one place and its implementation
15 // could be inlined, the previous attempts to do so made rustc
18 // * https://github.com/rust-lang/rust/pull/72189
19 // * https://github.com/rust-lang/rust/pull/79827
20 const fn size_align<T>() -> (usize, usize) {
21 (mem::size_of::<T>(), mem::align_of::<T>())
24 /// Layout of a block of memory.
26 /// An instance of `Layout` describes a particular layout of memory.
27 /// You build a `Layout` up as an input to give to an allocator.
29 /// All layouts have an associated size and a power-of-two alignment.
31 /// (Note that layouts are *not* required to have non-zero size,
32 /// even though `GlobalAlloc` requires that all memory requests
33 /// be non-zero in size. A caller must either ensure that conditions
34 /// like this are met, use specific allocators with looser
35 /// requirements, or use the more lenient `Allocator` interface.)
36 #[stable(feature = "alloc_layout", since = "1.28.0")]
37 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
38 #[lang = "alloc_layout"]
40 // size of the requested block of memory, measured in bytes.
43 // alignment of the requested block of memory, measured in bytes.
44 // we ensure that this is always a power-of-two, because API's
45 // like `posix_memalign` require it and it is a reasonable
46 // constraint to impose on Layout constructors.
48 // (However, we do not analogously require `align >= sizeof(void*)`,
49 // even though that is *also* a requirement of `posix_memalign`.)
54 /// Constructs a `Layout` from a given `size` and `align`,
55 /// or returns `LayoutError` if any of the following conditions
58 /// * `align` must not be zero,
60 /// * `align` must be a power of two,
62 /// * `size`, when rounded up to the nearest multiple of `align`,
63 /// must not overflow isize (i.e., the rounded value must be
64 /// less than or equal to `isize::MAX`).
65 #[stable(feature = "alloc_layout", since = "1.28.0")]
66 #[rustc_const_stable(feature = "const_alloc_layout_size_align", since = "1.50.0")]
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);
73 // SAFETY: just checked that align is a power of two.
74 Layout::from_size_valid_align(size, unsafe { ValidAlign::new_unchecked(align) })
78 const fn max_size_for_align(align: ValidAlign) -> usize {
79 // (power-of-two implies align != 0.)
81 // Rounded up size is:
82 // size_rounded_up = (size + align - 1) & !(align - 1);
84 // We know from above that align != 0. If adding (align - 1)
85 // does not overflow, then rounding up will be fine.
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.
91 // Above implies that checking for summation overflow is both
92 // necessary and sufficient.
93 isize::MAX as usize - (align.as_usize() - 1)
96 /// Internal helper constructor to skip revalidating alignment validity.
98 const fn from_size_valid_align(size: usize, align: ValidAlign) -> Result<Self, LayoutError> {
99 if size > Self::max_size_for_align(align) {
100 return Err(LayoutError);
103 // SAFETY: Layout::size invariants checked above.
104 Ok(Layout { size, align })
107 /// Creates a layout, bypassing all checks.
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")]
117 pub const unsafe fn from_size_align_unchecked(size: usize, align: usize) -> Self {
118 // SAFETY: the caller is required to uphold the preconditions.
119 unsafe { Layout { size, align: ValidAlign::new_unchecked(align) } }
122 /// The minimum size in bytes for a memory block of this layout.
123 #[stable(feature = "alloc_layout", since = "1.28.0")]
124 #[rustc_const_stable(feature = "const_alloc_layout_size_align", since = "1.50.0")]
127 pub const fn size(&self) -> usize {
131 /// The minimum byte alignment for a memory block of this layout.
132 #[stable(feature = "alloc_layout", since = "1.28.0")]
133 #[rustc_const_stable(feature = "const_alloc_layout_size_align", since = "1.50.0")]
134 #[must_use = "this returns the minimum alignment, \
135 without modifying the layout"]
137 pub const fn align(&self) -> usize {
138 self.align.as_usize()
141 /// Constructs a `Layout` suitable for holding a value of type `T`.
142 #[stable(feature = "alloc_layout", since = "1.28.0")]
143 #[rustc_const_stable(feature = "alloc_layout_const_new", since = "1.42.0")]
146 pub const fn new<T>() -> Self {
147 let (size, align) = size_align::<T>();
148 // SAFETY: if the type is instantiated, rustc already ensures that its
149 // layout is valid. Use the unchecked constructor to avoid inserting a
150 // panicking codepath that needs to be optimized out.
151 unsafe { Layout::from_size_align_unchecked(size, align) }
154 /// Produces layout describing a record that could be used to
155 /// allocate backing structure for `T` (which could be a trait
156 /// or other unsized type like a slice).
157 #[stable(feature = "alloc_layout", since = "1.28.0")]
160 pub fn for_value<T: ?Sized>(t: &T) -> Self {
161 let (size, align) = (mem::size_of_val(t), mem::align_of_val(t));
162 // SAFETY: see rationale in `new` for why this is using the unsafe variant
163 unsafe { Layout::from_size_align_unchecked(size, align) }
166 /// Produces layout describing a record that could be used to
167 /// allocate backing structure for `T` (which could be a trait
168 /// or other unsized type like a slice).
172 /// This function is only safe to call if the following conditions hold:
174 /// - If `T` is `Sized`, this function is always safe to call.
175 /// - If the unsized tail of `T` is:
176 /// - a [slice], then the length of the slice tail must be an initialized
177 /// integer, and the size of the *entire value*
178 /// (dynamic tail length + statically sized prefix) must fit in `isize`.
179 /// - a [trait object], then the vtable part of the pointer must point
180 /// to a valid vtable for the type `T` acquired by an unsizing coercion,
181 /// and the size of the *entire value*
182 /// (dynamic tail length + statically sized prefix) must fit in `isize`.
183 /// - an (unstable) [extern type], then this function is always safe to
184 /// call, but may panic or otherwise return the wrong value, as the
185 /// extern type's layout is not known. This is the same behavior as
186 /// [`Layout::for_value`] on a reference to an extern type tail.
187 /// - otherwise, it is conservatively not allowed to call this function.
189 /// [trait object]: ../../book/ch17-02-trait-objects.html
190 /// [extern type]: ../../unstable-book/language-features/extern-types.html
191 #[unstable(feature = "layout_for_ptr", issue = "69835")]
193 pub unsafe fn for_value_raw<T: ?Sized>(t: *const T) -> Self {
194 // SAFETY: we pass along the prerequisites of these functions to the caller
195 let (size, align) = unsafe { (mem::size_of_val_raw(t), mem::align_of_val_raw(t)) };
196 // SAFETY: see rationale in `new` for why this is using the unsafe variant
197 unsafe { Layout::from_size_align_unchecked(size, align) }
200 /// Creates a `NonNull` that is dangling, but well-aligned for this Layout.
202 /// Note that the pointer value may potentially represent a valid pointer,
203 /// which means this must not be used as a "not yet initialized"
204 /// sentinel value. Types that lazily allocate must track initialization by
205 /// some other means.
206 #[unstable(feature = "alloc_layout_extra", issue = "55724")]
207 #[rustc_const_unstable(feature = "alloc_layout_extra", issue = "55724")]
210 pub const fn dangling(&self) -> NonNull<u8> {
211 // SAFETY: align is guaranteed to be non-zero
212 unsafe { NonNull::new_unchecked(crate::ptr::invalid_mut::<u8>(self.align())) }
215 /// Creates a layout describing the record that can hold a value
216 /// of the same layout as `self`, but that also is aligned to
217 /// alignment `align` (measured in bytes).
219 /// If `self` already meets the prescribed alignment, then returns
222 /// Note that this method does not add any padding to the overall
223 /// size, regardless of whether the returned layout has a different
224 /// alignment. In other words, if `K` has size 16, `K.align_to(32)`
225 /// will *still* have size 16.
227 /// Returns an error if the combination of `self.size()` and the given
228 /// `align` violates the conditions listed in [`Layout::from_size_align`].
229 #[stable(feature = "alloc_layout_manipulation", since = "1.44.0")]
231 pub fn align_to(&self, align: usize) -> Result<Self, LayoutError> {
232 Layout::from_size_align(self.size(), cmp::max(self.align(), align))
235 /// Returns the amount of padding we must insert after `self`
236 /// to ensure that the following address will satisfy `align`
237 /// (measured in bytes).
239 /// e.g., if `self.size()` is 9, then `self.padding_needed_for(4)`
240 /// returns 3, because that is the minimum number of bytes of
241 /// padding required to get a 4-aligned address (assuming that the
242 /// corresponding memory block starts at a 4-aligned address).
244 /// The return value of this function has no meaning if `align` is
245 /// not a power-of-two.
247 /// Note that the utility of the returned value requires `align`
248 /// to be less than or equal to the alignment of the starting
249 /// address for the whole allocated block of memory. One way to
250 /// satisfy this constraint is to ensure `align <= self.align()`.
251 #[unstable(feature = "alloc_layout_extra", issue = "55724")]
252 #[rustc_const_unstable(feature = "const_alloc_layout", issue = "67521")]
253 #[must_use = "this returns the padding needed, \
254 without modifying the `Layout`"]
256 pub const fn padding_needed_for(&self, align: usize) -> usize {
257 let len = self.size();
259 // Rounded up value is:
260 // len_rounded_up = (len + align - 1) & !(align - 1);
261 // and then we return the padding difference: `len_rounded_up - len`.
263 // We use modular arithmetic throughout:
265 // 1. align is guaranteed to be > 0, so align - 1 is always
268 // 2. `len + align - 1` can overflow by at most `align - 1`,
269 // so the &-mask with `!(align - 1)` will ensure that in the
270 // case of overflow, `len_rounded_up` will itself be 0.
271 // Thus the returned padding, when added to `len`, yields 0,
272 // which trivially satisfies the alignment `align`.
274 // (Of course, attempts to allocate blocks of memory whose
275 // size and padding overflow in the above manner should cause
276 // the allocator to yield an error anyway.)
278 let len_rounded_up = len.wrapping_add(align).wrapping_sub(1) & !align.wrapping_sub(1);
279 len_rounded_up.wrapping_sub(len)
282 /// Creates a layout by rounding the size of this layout up to a multiple
283 /// of the layout's alignment.
285 /// This is equivalent to adding the result of `padding_needed_for`
286 /// to the layout's current size.
287 #[stable(feature = "alloc_layout_manipulation", since = "1.44.0")]
288 #[must_use = "this returns a new `Layout`, \
289 without modifying the original"]
291 pub fn pad_to_align(&self) -> Layout {
292 let pad = self.padding_needed_for(self.align());
293 // This cannot overflow. Quoting from the invariant of Layout:
294 // > `size`, when rounded up to the nearest multiple of `align`,
295 // > must not overflow isize (i.e., the rounded value must be
296 // > less than or equal to `isize::MAX`)
297 let new_size = self.size() + pad;
299 // SAFETY: padded size is guaranteed to not exceed `isize::MAX`.
300 unsafe { Layout::from_size_align_unchecked(new_size, self.align()) }
303 /// Creates a layout describing the record for `n` instances of
304 /// `self`, with a suitable amount of padding between each to
305 /// ensure that each instance is given its requested size and
306 /// alignment. On success, returns `(k, offs)` where `k` is the
307 /// layout of the array and `offs` is the distance between the start
308 /// of each element in the array.
310 /// On arithmetic overflow, returns `LayoutError`.
311 #[unstable(feature = "alloc_layout_extra", issue = "55724")]
313 pub fn repeat(&self, n: usize) -> Result<(Self, usize), LayoutError> {
314 // This cannot overflow. Quoting from the invariant of Layout:
315 // > `size`, when rounded up to the nearest multiple of `align`,
316 // > must not overflow isize (i.e., the rounded value must be
317 // > less than or equal to `isize::MAX`)
318 let padded_size = self.size() + self.padding_needed_for(self.align());
319 let alloc_size = padded_size.checked_mul(n).ok_or(LayoutError)?;
321 // The safe constructor is called here to enforce the isize size limit.
322 Layout::from_size_valid_align(alloc_size, self.align).map(|layout| (layout, padded_size))
325 /// Creates a layout describing the record for `self` followed by
326 /// `next`, including any necessary padding to ensure that `next`
327 /// will be properly aligned, but *no trailing padding*.
329 /// In order to match C representation layout `repr(C)`, you should
330 /// call `pad_to_align` after extending the layout with all fields.
331 /// (There is no way to match the default Rust representation
332 /// layout `repr(Rust)`, as it is unspecified.)
334 /// Note that the alignment of the resulting layout will be the maximum of
335 /// those of `self` and `next`, in order to ensure alignment of both parts.
337 /// Returns `Ok((k, offset))`, where `k` is layout of the concatenated
338 /// record and `offset` is the relative location, in bytes, of the
339 /// start of the `next` embedded within the concatenated record
340 /// (assuming that the record itself starts at offset 0).
342 /// On arithmetic overflow, returns `LayoutError`.
346 /// To calculate the layout of a `#[repr(C)]` structure and the offsets of
347 /// the fields from its fields' layouts:
350 /// # use std::alloc::{Layout, LayoutError};
351 /// pub fn repr_c(fields: &[Layout]) -> Result<(Layout, Vec<usize>), LayoutError> {
352 /// let mut offsets = Vec::new();
353 /// let mut layout = Layout::from_size_align(0, 1)?;
354 /// for &field in fields {
355 /// let (new_layout, offset) = layout.extend(field)?;
356 /// layout = new_layout;
357 /// offsets.push(offset);
359 /// // Remember to finalize with `pad_to_align`!
360 /// Ok((layout.pad_to_align(), offsets))
362 /// # // test that it works
363 /// # #[repr(C)] struct S { a: u64, b: u32, c: u16, d: u32 }
364 /// # let s = Layout::new::<S>();
365 /// # let u16 = Layout::new::<u16>();
366 /// # let u32 = Layout::new::<u32>();
367 /// # let u64 = Layout::new::<u64>();
368 /// # assert_eq!(repr_c(&[u64, u32, u16, u32]), Ok((s, vec![0, 8, 12, 16])));
370 #[stable(feature = "alloc_layout_manipulation", since = "1.44.0")]
372 pub fn extend(&self, next: Self) -> Result<(Self, usize), LayoutError> {
373 let new_align = cmp::max(self.align, next.align);
374 let pad = self.padding_needed_for(next.align());
376 let offset = self.size().checked_add(pad).ok_or(LayoutError)?;
377 let new_size = offset.checked_add(next.size()).ok_or(LayoutError)?;
379 // The safe constructor is called here to enforce the isize size limit.
380 let layout = Layout::from_size_valid_align(new_size, new_align)?;
384 /// Creates a layout describing the record for `n` instances of
385 /// `self`, with no padding between each instance.
387 /// Note that, unlike `repeat`, `repeat_packed` does not guarantee
388 /// that the repeated instances of `self` will be properly
389 /// aligned, even if a given instance of `self` is properly
390 /// aligned. In other words, if the layout returned by
391 /// `repeat_packed` is used to allocate an array, it is not
392 /// guaranteed that all elements in the array will be properly
395 /// On arithmetic overflow, returns `LayoutError`.
396 #[unstable(feature = "alloc_layout_extra", issue = "55724")]
398 pub fn repeat_packed(&self, n: usize) -> Result<Self, LayoutError> {
399 let size = self.size().checked_mul(n).ok_or(LayoutError)?;
400 // The safe constructor is called here to enforce the isize size limit.
401 Layout::from_size_valid_align(size, self.align)
404 /// Creates a layout describing the record for `self` followed by
405 /// `next` with no additional padding between the two. Since no
406 /// padding is inserted, the alignment of `next` is irrelevant,
407 /// and is not incorporated *at all* into the resulting layout.
409 /// On arithmetic overflow, returns `LayoutError`.
410 #[unstable(feature = "alloc_layout_extra", issue = "55724")]
412 pub fn extend_packed(&self, next: Self) -> Result<Self, LayoutError> {
413 let new_size = self.size().checked_add(next.size()).ok_or(LayoutError)?;
414 // The safe constructor is called here to enforce the isize size limit.
415 Layout::from_size_valid_align(new_size, self.align)
418 /// Creates a layout describing the record for a `[T; n]`.
420 /// On arithmetic overflow or when the total size would exceed
421 /// `isize::MAX`, returns `LayoutError`.
422 #[stable(feature = "alloc_layout_manipulation", since = "1.44.0")]
424 pub fn array<T>(n: usize) -> Result<Self, LayoutError> {
425 // Reduce the amount of code we need to monomorphize per `T`.
426 return inner(mem::size_of::<T>(), ValidAlign::of::<T>(), n);
429 fn inner(element_size: usize, align: ValidAlign, n: usize) -> Result<Layout, LayoutError> {
430 // We need to check two things about the size:
431 // - That the total size won't overflow a `usize`, and
432 // - That the total size still fits in an `isize`.
433 // By using division we can check them both with a single threshold.
434 // That'd usually be a bad idea, but thankfully here the element size
435 // and alignment are constants, so the compiler will fold all of it.
436 if element_size != 0 && n > Layout::max_size_for_align(align) / element_size {
437 return Err(LayoutError);
440 let array_size = element_size * n;
442 // SAFETY: We just checked above that the `array_size` will not
443 // exceed `isize::MAX` even when rounded up to the alignment.
444 // And `ValidAlign` guarantees it's a power of two.
445 unsafe { Ok(Layout::from_size_align_unchecked(array_size, align.as_usize())) }
450 #[stable(feature = "alloc_layout", since = "1.28.0")]
453 note = "Name does not follow std convention, use LayoutError",
454 suggestion = "LayoutError"
456 pub type LayoutErr = LayoutError;
458 /// The parameters given to `Layout::from_size_align`
459 /// or some other `Layout` constructor
460 /// do not satisfy its documented constraints.
461 #[stable(feature = "alloc_layout_error", since = "1.50.0")]
463 #[derive(Clone, PartialEq, Eq, Debug)]
464 pub struct LayoutError;
466 #[cfg(not(bootstrap))]
467 #[stable(feature = "alloc_layout", since = "1.28.0")]
468 impl Error for LayoutError {}
470 // (we need this for downstream impl of trait Error)
471 #[stable(feature = "alloc_layout", since = "1.28.0")]
472 impl fmt::Display for LayoutError {
473 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
474 f.write_str("invalid parameters to Layout::from_size_align")