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