]> git.lizzy.rs Git - rust.git/blob - src/libcore/alloc.rs
Rollup merge of #69587 - petrochenkov:reqname, r=Centril
[rust.git] / src / libcore / alloc.rs
1 //! Memory allocation APIs
2
3 // ignore-tidy-undocumented-unsafe
4
5 #![stable(feature = "alloc_module", since = "1.28.0")]
6
7 use crate::cmp;
8 use crate::fmt;
9 use crate::mem;
10 use crate::num::NonZeroUsize;
11 use crate::ptr::{self, NonNull};
12 use crate::usize;
13
14 /// Represents the combination of a starting address and
15 /// a total capacity of the returned block.
16 #[unstable(feature = "allocator_api", issue = "32838")]
17 #[derive(Debug)]
18 pub struct Excess(pub NonNull<u8>, pub usize);
19
20 const fn size_align<T>() -> (usize, usize) {
21     (mem::size_of::<T>(), mem::align_of::<T>())
22 }
23
24 /// Layout of a block of memory.
25 ///
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.
28 ///
29 /// All layouts have an associated non-negative size and a
30 /// power-of-two alignment.
31 ///
32 /// (Note however that layouts are *not* required to have positive
33 /// size, even though many allocators require that all memory
34 /// requests have positive size. A caller to the `AllocRef::alloc`
35 /// method must either ensure that conditions like this are met, or
36 /// use specific allocators with looser requirements.)
37 #[stable(feature = "alloc_layout", since = "1.28.0")]
38 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
39 #[lang = "alloc_layout"]
40 pub 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_: NonZeroUsize,
52 }
53
54 impl Layout {
55     /// Constructs a `Layout` from a given `size` and `align`,
56     /// or returns `LayoutErr` 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 (i.e., the rounded value must be less than
65     ///    `usize::MAX`).
66     #[stable(feature = "alloc_layout", since = "1.28.0")]
67     #[rustc_const_unstable(feature = "const_alloc_layout", issue = "67521")]
68     #[inline]
69     pub const fn from_size_align(size: usize, align: usize) -> Result<Self, LayoutErr> {
70         if !align.is_power_of_two() {
71             return Err(LayoutErr { private: () });
72         }
73
74         // (power-of-two implies align != 0.)
75
76         // Rounded up size is:
77         //   size_rounded_up = (size + align - 1) & !(align - 1);
78         //
79         // We know from above that align != 0. If adding (align - 1)
80         // does not overflow, then rounding up will be fine.
81         //
82         // Conversely, &-masking with !(align - 1) will subtract off
83         // only low-order-bits. Thus if overflow occurs with the sum,
84         // the &-mask cannot subtract enough to undo that overflow.
85         //
86         // Above implies that checking for summation overflow is both
87         // necessary and sufficient.
88         if size > usize::MAX - (align - 1) {
89             return Err(LayoutErr { private: () });
90         }
91
92         unsafe { Ok(Layout::from_size_align_unchecked(size, align)) }
93     }
94
95     /// Creates a layout, bypassing all checks.
96     ///
97     /// # Safety
98     ///
99     /// This function is unsafe as it does not verify the preconditions from
100     /// [`Layout::from_size_align`](#method.from_size_align).
101     #[stable(feature = "alloc_layout", since = "1.28.0")]
102     #[rustc_const_stable(feature = "alloc_layout", since = "1.28.0")]
103     #[inline]
104     pub const unsafe fn from_size_align_unchecked(size: usize, align: usize) -> Self {
105         Layout { size_: size, align_: NonZeroUsize::new_unchecked(align) }
106     }
107
108     /// The minimum size in bytes for a memory block of this layout.
109     #[stable(feature = "alloc_layout", since = "1.28.0")]
110     #[rustc_const_unstable(feature = "const_alloc_layout", issue = "67521")]
111     #[inline]
112     pub const fn size(&self) -> usize {
113         self.size_
114     }
115
116     /// The minimum byte alignment for a memory block of this layout.
117     #[stable(feature = "alloc_layout", since = "1.28.0")]
118     #[rustc_const_unstable(feature = "const_alloc_layout", issue = "67521")]
119     #[inline]
120     pub const fn align(&self) -> usize {
121         self.align_.get()
122     }
123
124     /// Constructs a `Layout` suitable for holding a value of type `T`.
125     #[stable(feature = "alloc_layout", since = "1.28.0")]
126     #[rustc_const_stable(feature = "alloc_layout_const_new", since = "1.42.0")]
127     #[inline]
128     pub const fn new<T>() -> Self {
129         let (size, align) = size_align::<T>();
130         // Note that the align is guaranteed by rustc to be a power of two and
131         // the size+align combo is guaranteed to fit in our address space. As a
132         // result use the unchecked constructor here to avoid inserting code
133         // that panics if it isn't optimized well enough.
134         unsafe { Layout::from_size_align_unchecked(size, align) }
135     }
136
137     /// Produces layout describing a record that could be used to
138     /// allocate backing structure for `T` (which could be a trait
139     /// or other unsized type like a slice).
140     #[stable(feature = "alloc_layout", since = "1.28.0")]
141     #[inline]
142     pub fn for_value<T: ?Sized>(t: &T) -> Self {
143         let (size, align) = (mem::size_of_val(t), mem::align_of_val(t));
144         // See rationale in `new` for why this is using an unsafe variant below
145         debug_assert!(Layout::from_size_align(size, align).is_ok());
146         unsafe { Layout::from_size_align_unchecked(size, align) }
147     }
148
149     /// Creates a layout describing the record that can hold a value
150     /// of the same layout as `self`, but that also is aligned to
151     /// alignment `align` (measured in bytes).
152     ///
153     /// If `self` already meets the prescribed alignment, then returns
154     /// `self`.
155     ///
156     /// Note that this method does not add any padding to the overall
157     /// size, regardless of whether the returned layout has a different
158     /// alignment. In other words, if `K` has size 16, `K.align_to(32)`
159     /// will *still* have size 16.
160     ///
161     /// Returns an error if the combination of `self.size()` and the given
162     /// `align` violates the conditions listed in
163     /// [`Layout::from_size_align`](#method.from_size_align).
164     #[unstable(feature = "alloc_layout_extra", issue = "55724")]
165     #[inline]
166     pub fn align_to(&self, align: usize) -> Result<Self, LayoutErr> {
167         Layout::from_size_align(self.size(), cmp::max(self.align(), align))
168     }
169
170     /// Returns the amount of padding we must insert after `self`
171     /// to ensure that the following address will satisfy `align`
172     /// (measured in bytes).
173     ///
174     /// e.g., if `self.size()` is 9, then `self.padding_needed_for(4)`
175     /// returns 3, because that is the minimum number of bytes of
176     /// padding required to get a 4-aligned address (assuming that the
177     /// corresponding memory block starts at a 4-aligned address).
178     ///
179     /// The return value of this function has no meaning if `align` is
180     /// not a power-of-two.
181     ///
182     /// Note that the utility of the returned value requires `align`
183     /// to be less than or equal to the alignment of the starting
184     /// address for the whole allocated block of memory. One way to
185     /// satisfy this constraint is to ensure `align <= self.align()`.
186     #[unstable(feature = "alloc_layout_extra", issue = "55724")]
187     #[rustc_const_unstable(feature = "const_alloc_layout", issue = "67521")]
188     #[inline]
189     pub const fn padding_needed_for(&self, align: usize) -> usize {
190         let len = self.size();
191
192         // Rounded up value is:
193         //   len_rounded_up = (len + align - 1) & !(align - 1);
194         // and then we return the padding difference: `len_rounded_up - len`.
195         //
196         // We use modular arithmetic throughout:
197         //
198         // 1. align is guaranteed to be > 0, so align - 1 is always
199         //    valid.
200         //
201         // 2. `len + align - 1` can overflow by at most `align - 1`,
202         //    so the &-mask with `!(align - 1)` will ensure that in the
203         //    case of overflow, `len_rounded_up` will itself be 0.
204         //    Thus the returned padding, when added to `len`, yields 0,
205         //    which trivially satisfies the alignment `align`.
206         //
207         // (Of course, attempts to allocate blocks of memory whose
208         // size and padding overflow in the above manner should cause
209         // the allocator to yield an error anyway.)
210
211         let len_rounded_up = len.wrapping_add(align).wrapping_sub(1) & !align.wrapping_sub(1);
212         len_rounded_up.wrapping_sub(len)
213     }
214
215     /// Creates a layout by rounding the size of this layout up to a multiple
216     /// of the layout's alignment.
217     ///
218     /// This is equivalent to adding the result of `padding_needed_for`
219     /// to the layout's current size.
220     #[unstable(feature = "alloc_layout_extra", issue = "55724")]
221     #[inline]
222     pub fn pad_to_align(&self) -> Layout {
223         let pad = self.padding_needed_for(self.align());
224         // This cannot overflow. Quoting from the invariant of Layout:
225         // > `size`, when rounded up to the nearest multiple of `align`,
226         // > must not overflow (i.e., the rounded value must be less than
227         // > `usize::MAX`)
228         let new_size = self.size() + pad;
229
230         Layout::from_size_align(new_size, self.align()).unwrap()
231     }
232
233     /// Creates a layout describing the record for `n` instances of
234     /// `self`, with a suitable amount of padding between each to
235     /// ensure that each instance is given its requested size and
236     /// alignment. On success, returns `(k, offs)` where `k` is the
237     /// layout of the array and `offs` is the distance between the start
238     /// of each element in the array.
239     ///
240     /// On arithmetic overflow, returns `LayoutErr`.
241     #[unstable(feature = "alloc_layout_extra", issue = "55724")]
242     #[inline]
243     pub fn repeat(&self, n: usize) -> Result<(Self, usize), LayoutErr> {
244         // Warning, removing the checked_add here led to segfaults in #67174. Further
245         // analysis in #69225 seems to indicate that this is an LTO-related
246         // miscompilation, so #67174 might be able to be reapplied in the future.
247         let padded_size = self
248             .size()
249             .checked_add(self.padding_needed_for(self.align()))
250             .ok_or(LayoutErr { private: () })?;
251         let alloc_size = padded_size.checked_mul(n).ok_or(LayoutErr { private: () })?;
252
253         unsafe {
254             // self.align is already known to be valid and alloc_size has been
255             // padded already.
256             Ok((Layout::from_size_align_unchecked(alloc_size, self.align()), padded_size))
257         }
258     }
259
260     /// Creates a layout describing the record for `self` followed by
261     /// `next`, including any necessary padding to ensure that `next`
262     /// will be properly aligned. Note that the resulting layout will
263     /// satisfy the alignment properties of both `self` and `next`.
264     ///
265     /// The resulting layout will be the same as that of a C struct containing
266     /// two fields with the layouts of `self` and `next`, in that order.
267     ///
268     /// Returns `Some((k, offset))`, where `k` is layout of the concatenated
269     /// record and `offset` is the relative location, in bytes, of the
270     /// start of the `next` embedded within the concatenated record
271     /// (assuming that the record itself starts at offset 0).
272     ///
273     /// On arithmetic overflow, returns `LayoutErr`.
274     #[unstable(feature = "alloc_layout_extra", issue = "55724")]
275     #[inline]
276     pub fn extend(&self, next: Self) -> Result<(Self, usize), LayoutErr> {
277         let new_align = cmp::max(self.align(), next.align());
278         let pad = self.padding_needed_for(next.align());
279
280         let offset = self.size().checked_add(pad).ok_or(LayoutErr { private: () })?;
281         let new_size = offset.checked_add(next.size()).ok_or(LayoutErr { private: () })?;
282
283         let layout = Layout::from_size_align(new_size, new_align)?;
284         Ok((layout, offset))
285     }
286
287     /// Creates a layout describing the record for `n` instances of
288     /// `self`, with no padding between each instance.
289     ///
290     /// Note that, unlike `repeat`, `repeat_packed` does not guarantee
291     /// that the repeated instances of `self` will be properly
292     /// aligned, even if a given instance of `self` is properly
293     /// aligned. In other words, if the layout returned by
294     /// `repeat_packed` is used to allocate an array, it is not
295     /// guaranteed that all elements in the array will be properly
296     /// aligned.
297     ///
298     /// On arithmetic overflow, returns `LayoutErr`.
299     #[unstable(feature = "alloc_layout_extra", issue = "55724")]
300     #[inline]
301     pub fn repeat_packed(&self, n: usize) -> Result<Self, LayoutErr> {
302         let size = self.size().checked_mul(n).ok_or(LayoutErr { private: () })?;
303         Layout::from_size_align(size, self.align())
304     }
305
306     /// Creates a layout describing the record for `self` followed by
307     /// `next` with no additional padding between the two. Since no
308     /// padding is inserted, the alignment of `next` is irrelevant,
309     /// and is not incorporated *at all* into the resulting layout.
310     ///
311     /// On arithmetic overflow, returns `LayoutErr`.
312     #[unstable(feature = "alloc_layout_extra", issue = "55724")]
313     #[inline]
314     pub fn extend_packed(&self, next: Self) -> Result<Self, LayoutErr> {
315         let new_size = self.size().checked_add(next.size()).ok_or(LayoutErr { private: () })?;
316         Layout::from_size_align(new_size, self.align())
317     }
318
319     /// Creates a layout describing the record for a `[T; n]`.
320     ///
321     /// On arithmetic overflow, returns `LayoutErr`.
322     #[unstable(feature = "alloc_layout_extra", issue = "55724")]
323     #[inline]
324     pub fn array<T>(n: usize) -> Result<Self, LayoutErr> {
325         Layout::new::<T>().repeat(n).map(|(k, offs)| {
326             debug_assert!(offs == mem::size_of::<T>());
327             k
328         })
329     }
330 }
331
332 /// The parameters given to `Layout::from_size_align`
333 /// or some other `Layout` constructor
334 /// do not satisfy its documented constraints.
335 #[stable(feature = "alloc_layout", since = "1.28.0")]
336 #[derive(Clone, PartialEq, Eq, Debug)]
337 pub struct LayoutErr {
338     private: (),
339 }
340
341 // (we need this for downstream impl of trait Error)
342 #[stable(feature = "alloc_layout", since = "1.28.0")]
343 impl fmt::Display for LayoutErr {
344     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
345         f.write_str("invalid parameters to Layout::from_size_align")
346     }
347 }
348
349 /// The `AllocErr` error indicates an allocation failure
350 /// that may be due to resource exhaustion or to
351 /// something wrong when combining the given input arguments with this
352 /// allocator.
353 #[unstable(feature = "allocator_api", issue = "32838")]
354 #[derive(Clone, PartialEq, Eq, Debug)]
355 pub struct AllocErr;
356
357 // (we need this for downstream impl of trait Error)
358 #[unstable(feature = "allocator_api", issue = "32838")]
359 impl fmt::Display for AllocErr {
360     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
361         f.write_str("memory allocation failed")
362     }
363 }
364
365 /// The `CannotReallocInPlace` error is used when [`grow_in_place`] or
366 /// [`shrink_in_place`] were unable to reuse the given memory block for
367 /// a requested layout.
368 ///
369 /// [`grow_in_place`]: ./trait.AllocRef.html#method.grow_in_place
370 /// [`shrink_in_place`]: ./trait.AllocRef.html#method.shrink_in_place
371 #[unstable(feature = "allocator_api", issue = "32838")]
372 #[derive(Clone, PartialEq, Eq, Debug)]
373 pub struct CannotReallocInPlace;
374
375 #[unstable(feature = "allocator_api", issue = "32838")]
376 impl CannotReallocInPlace {
377     pub fn description(&self) -> &str {
378         "cannot reallocate allocator's memory in place"
379     }
380 }
381
382 // (we need this for downstream impl of trait Error)
383 #[unstable(feature = "allocator_api", issue = "32838")]
384 impl fmt::Display for CannotReallocInPlace {
385     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
386         write!(f, "{}", self.description())
387     }
388 }
389
390 /// A memory allocator that can be registered as the standard library’s default
391 /// through the `#[global_allocator]` attribute.
392 ///
393 /// Some of the methods require that a memory block be *currently
394 /// allocated* via an allocator. This means that:
395 ///
396 /// * the starting address for that memory block was previously
397 ///   returned by a previous call to an allocation method
398 ///   such as `alloc`, and
399 ///
400 /// * the memory block has not been subsequently deallocated, where
401 ///   blocks are deallocated either by being passed to a deallocation
402 ///   method such as `dealloc` or by being
403 ///   passed to a reallocation method that returns a non-null pointer.
404 ///
405 ///
406 /// # Example
407 ///
408 /// ```no_run
409 /// use std::alloc::{GlobalAlloc, Layout, alloc};
410 /// use std::ptr::null_mut;
411 ///
412 /// struct MyAllocator;
413 ///
414 /// unsafe impl GlobalAlloc for MyAllocator {
415 ///     unsafe fn alloc(&self, _layout: Layout) -> *mut u8 { null_mut() }
416 ///     unsafe fn dealloc(&self, _ptr: *mut u8, _layout: Layout) {}
417 /// }
418 ///
419 /// #[global_allocator]
420 /// static A: MyAllocator = MyAllocator;
421 ///
422 /// fn main() {
423 ///     unsafe {
424 ///         assert!(alloc(Layout::new::<u32>()).is_null())
425 ///     }
426 /// }
427 /// ```
428 ///
429 /// # Safety
430 ///
431 /// The `GlobalAlloc` trait is an `unsafe` trait for a number of reasons, and
432 /// implementors must ensure that they adhere to these contracts:
433 ///
434 /// * It's undefined behavior if global allocators unwind. This restriction may
435 ///   be lifted in the future, but currently a panic from any of these
436 ///   functions may lead to memory unsafety.
437 ///
438 /// * `Layout` queries and calculations in general must be correct. Callers of
439 ///   this trait are allowed to rely on the contracts defined on each method,
440 ///   and implementors must ensure such contracts remain true.
441 #[stable(feature = "global_alloc", since = "1.28.0")]
442 pub unsafe trait GlobalAlloc {
443     /// Allocate memory as described by the given `layout`.
444     ///
445     /// Returns a pointer to newly-allocated memory,
446     /// or null to indicate allocation failure.
447     ///
448     /// # Safety
449     ///
450     /// This function is unsafe because undefined behavior can result
451     /// if the caller does not ensure that `layout` has non-zero size.
452     ///
453     /// (Extension subtraits might provide more specific bounds on
454     /// behavior, e.g., guarantee a sentinel address or a null pointer
455     /// in response to a zero-size allocation request.)
456     ///
457     /// The allocated block of memory may or may not be initialized.
458     ///
459     /// # Errors
460     ///
461     /// Returning a null pointer indicates that either memory is exhausted
462     /// or `layout` does not meet this allocator's size or alignment constraints.
463     ///
464     /// Implementations are encouraged to return null on memory
465     /// exhaustion rather than aborting, but this is not
466     /// a strict requirement. (Specifically: it is *legal* to
467     /// implement this trait atop an underlying native allocation
468     /// library that aborts on memory exhaustion.)
469     ///
470     /// Clients wishing to abort computation in response to an
471     /// allocation error are encouraged to call the [`handle_alloc_error`] function,
472     /// rather than directly invoking `panic!` or similar.
473     ///
474     /// [`handle_alloc_error`]: ../../alloc/alloc/fn.handle_alloc_error.html
475     #[stable(feature = "global_alloc", since = "1.28.0")]
476     unsafe fn alloc(&self, layout: Layout) -> *mut u8;
477
478     /// Deallocate the block of memory at the given `ptr` pointer with the given `layout`.
479     ///
480     /// # Safety
481     ///
482     /// This function is unsafe because undefined behavior can result
483     /// if the caller does not ensure all of the following:
484     ///
485     /// * `ptr` must denote a block of memory currently allocated via
486     ///   this allocator,
487     ///
488     /// * `layout` must be the same layout that was used
489     ///   to allocate that block of memory,
490     #[stable(feature = "global_alloc", since = "1.28.0")]
491     unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout);
492
493     /// Behaves like `alloc`, but also ensures that the contents
494     /// are set to zero before being returned.
495     ///
496     /// # Safety
497     ///
498     /// This function is unsafe for the same reasons that `alloc` is.
499     /// However the allocated block of memory is guaranteed to be initialized.
500     ///
501     /// # Errors
502     ///
503     /// Returning a null pointer indicates that either memory is exhausted
504     /// or `layout` does not meet allocator's size or alignment constraints,
505     /// just as in `alloc`.
506     ///
507     /// Clients wishing to abort computation in response to an
508     /// allocation error are encouraged to call the [`handle_alloc_error`] function,
509     /// rather than directly invoking `panic!` or similar.
510     ///
511     /// [`handle_alloc_error`]: ../../alloc/alloc/fn.handle_alloc_error.html
512     #[stable(feature = "global_alloc", since = "1.28.0")]
513     unsafe fn alloc_zeroed(&self, layout: Layout) -> *mut u8 {
514         let size = layout.size();
515         let ptr = self.alloc(layout);
516         if !ptr.is_null() {
517             ptr::write_bytes(ptr, 0, size);
518         }
519         ptr
520     }
521
522     /// Shrink or grow a block of memory to the given `new_size`.
523     /// The block is described by the given `ptr` pointer and `layout`.
524     ///
525     /// If this returns a non-null pointer, then ownership of the memory block
526     /// referenced by `ptr` has been transferred to this allocator.
527     /// The memory may or may not have been deallocated,
528     /// and should be considered unusable (unless of course it was
529     /// transferred back to the caller again via the return value of
530     /// this method). The new memory block is allocated with `layout`, but
531     /// with the `size` updated to `new_size`.
532     ///
533     /// If this method returns null, then ownership of the memory
534     /// block has not been transferred to this allocator, and the
535     /// contents of the memory block are unaltered.
536     ///
537     /// # Safety
538     ///
539     /// This function is unsafe because undefined behavior can result
540     /// if the caller does not ensure all of the following:
541     ///
542     /// * `ptr` must be currently allocated via this allocator,
543     ///
544     /// * `layout` must be the same layout that was used
545     ///   to allocate that block of memory,
546     ///
547     /// * `new_size` must be greater than zero.
548     ///
549     /// * `new_size`, when rounded up to the nearest multiple of `layout.align()`,
550     ///   must not overflow (i.e., the rounded value must be less than `usize::MAX`).
551     ///
552     /// (Extension subtraits might provide more specific bounds on
553     /// behavior, e.g., guarantee a sentinel address or a null pointer
554     /// in response to a zero-size allocation request.)
555     ///
556     /// # Errors
557     ///
558     /// Returns null if the new layout does not meet the size
559     /// and alignment constraints of the allocator, or if reallocation
560     /// otherwise fails.
561     ///
562     /// Implementations are encouraged to return null on memory
563     /// exhaustion rather than panicking or aborting, but this is not
564     /// a strict requirement. (Specifically: it is *legal* to
565     /// implement this trait atop an underlying native allocation
566     /// library that aborts on memory exhaustion.)
567     ///
568     /// Clients wishing to abort computation in response to a
569     /// reallocation error are encouraged to call the [`handle_alloc_error`] function,
570     /// rather than directly invoking `panic!` or similar.
571     ///
572     /// [`handle_alloc_error`]: ../../alloc/alloc/fn.handle_alloc_error.html
573     #[stable(feature = "global_alloc", since = "1.28.0")]
574     unsafe fn realloc(&self, ptr: *mut u8, layout: Layout, new_size: usize) -> *mut u8 {
575         let new_layout = Layout::from_size_align_unchecked(new_size, layout.align());
576         let new_ptr = self.alloc(new_layout);
577         if !new_ptr.is_null() {
578             ptr::copy_nonoverlapping(ptr, new_ptr, cmp::min(layout.size(), new_size));
579             self.dealloc(ptr, layout);
580         }
581         new_ptr
582     }
583 }
584
585 /// An implementation of `AllocRef` can allocate, reallocate, and
586 /// deallocate arbitrary blocks of data described via `Layout`.
587 ///
588 /// `AllocRef` is designed to be implemented on ZSTs, references, or
589 /// smart pointers because having an allocator like `MyAlloc([u8; N])`
590 /// cannot be moved, without updating the pointers to the allocated
591 /// memory.
592 ///
593 /// Some of the methods require that a memory block be *currently
594 /// allocated* via an allocator. This means that:
595 ///
596 /// * the starting address for that memory block was previously
597 ///   returned by a previous call to an allocation method (`alloc`,
598 ///   `alloc_zeroed`, `alloc_excess`) or reallocation method
599 ///   (`realloc`, `realloc_excess`), and
600 ///
601 /// * the memory block has not been subsequently deallocated, where
602 ///   blocks are deallocated either by being passed to a deallocation
603 ///   method (`dealloc`, `dealloc_one`, `dealloc_array`) or by being
604 ///   passed to a reallocation method (see above) that returns `Ok`.
605 ///
606 /// A note regarding zero-sized types and zero-sized layouts: many
607 /// methods in the `AllocRef` trait state that allocation requests
608 /// must be non-zero size, or else undefined behavior can result.
609 ///
610 /// * If an `AllocRef` implementation chooses to return `Ok` in this
611 ///   case (i.e., the pointer denotes a zero-sized inaccessible block)
612 ///   then that returned pointer must be considered "currently
613 ///   allocated". On such an allocator, *all* methods that take
614 ///   currently-allocated pointers as inputs must accept these
615 ///   zero-sized pointers, *without* causing undefined behavior.
616 ///
617 /// * In other words, if a zero-sized pointer can flow out of an
618 ///   allocator, then that allocator must likewise accept that pointer
619 ///   flowing back into its deallocation and reallocation methods.
620 ///
621 /// Some of the methods require that a layout *fit* a memory block.
622 /// What it means for a layout to "fit" a memory block means (or
623 /// equivalently, for a memory block to "fit" a layout) is that the
624 /// following two conditions must hold:
625 ///
626 /// 1. The block's starting address must be aligned to `layout.align()`.
627 ///
628 /// 2. The block's size must fall in the range `[use_min, use_max]`, where:
629 ///
630 ///    * `use_min` is `self.usable_size(layout).0`, and
631 ///
632 ///    * `use_max` is the capacity that was (or would have been)
633 ///      returned when (if) the block was allocated via a call to
634 ///      `alloc_excess` or `realloc_excess`.
635 ///
636 /// Note that:
637 ///
638 ///  * the size of the layout most recently used to allocate the block
639 ///    is guaranteed to be in the range `[use_min, use_max]`, and
640 ///
641 ///  * a lower-bound on `use_max` can be safely approximated by a call to
642 ///    `usable_size`.
643 ///
644 ///  * if a layout `k` fits a memory block (denoted by `ptr`)
645 ///    currently allocated via an allocator `a`, then it is legal to
646 ///    use that layout to deallocate it, i.e., `a.dealloc(ptr, k);`.
647 ///
648 /// # Safety
649 ///
650 /// The `AllocRef` trait is an `unsafe` trait for a number of reasons, and
651 /// implementors must ensure that they adhere to these contracts:
652 ///
653 /// * Pointers returned from allocation functions must point to valid memory and
654 ///   retain their validity until at least one instance of `AllocRef` is dropped
655 ///   itself.
656 ///
657 /// * Cloning or moving the allocator must not invalidate pointers returned
658 ///   from this allocator. Cloning must return a reference to the same allocator.
659 ///
660 /// * `Layout` queries and calculations in general must be correct. Callers of
661 ///   this trait are allowed to rely on the contracts defined on each method,
662 ///   and implementors must ensure such contracts remain true.
663 ///
664 /// Note that this list may get tweaked over time as clarifications are made in
665 /// the future.
666 #[unstable(feature = "allocator_api", issue = "32838")]
667 pub unsafe trait AllocRef {
668     // (Note: some existing allocators have unspecified but well-defined
669     // behavior in response to a zero size allocation request ;
670     // e.g., in C, `malloc` of 0 will either return a null pointer or a
671     // unique pointer, but will not have arbitrary undefined
672     // behavior.
673     // However in jemalloc for example,
674     // `mallocx(0)` is documented as undefined behavior.)
675
676     /// Returns a pointer meeting the size and alignment guarantees of
677     /// `layout`.
678     ///
679     /// If this method returns an `Ok(addr)`, then the `addr` returned
680     /// will be non-null address pointing to a block of storage
681     /// suitable for holding an instance of `layout`.
682     ///
683     /// The returned block of storage may or may not have its contents
684     /// initialized. (Extension subtraits might restrict this
685     /// behavior, e.g., to ensure initialization to particular sets of
686     /// bit patterns.)
687     ///
688     /// # Safety
689     ///
690     /// This function is unsafe because undefined behavior can result
691     /// if the caller does not ensure that `layout` has non-zero size.
692     ///
693     /// (Extension subtraits might provide more specific bounds on
694     /// behavior, e.g., guarantee a sentinel address or a null pointer
695     /// in response to a zero-size allocation request.)
696     ///
697     /// # Errors
698     ///
699     /// Returning `Err` indicates that either memory is exhausted or
700     /// `layout` does not meet allocator's size or alignment
701     /// constraints.
702     ///
703     /// Implementations are encouraged to return `Err` on memory
704     /// exhaustion rather than panicking or aborting, but this is not
705     /// a strict requirement. (Specifically: it is *legal* to
706     /// implement this trait atop an underlying native allocation
707     /// library that aborts on memory exhaustion.)
708     ///
709     /// Clients wishing to abort computation in response to an
710     /// allocation error are encouraged to call the [`handle_alloc_error`] function,
711     /// rather than directly invoking `panic!` or similar.
712     ///
713     /// [`handle_alloc_error`]: ../../alloc/alloc/fn.handle_alloc_error.html
714     unsafe fn alloc(&mut self, layout: Layout) -> Result<NonNull<u8>, AllocErr>;
715
716     /// Deallocate the memory referenced by `ptr`.
717     ///
718     /// # Safety
719     ///
720     /// This function is unsafe because undefined behavior can result
721     /// if the caller does not ensure all of the following:
722     ///
723     /// * `ptr` must denote a block of memory currently allocated via
724     ///   this allocator,
725     ///
726     /// * `layout` must *fit* that block of memory,
727     ///
728     /// * In addition to fitting the block of memory `layout`, the
729     ///   alignment of the `layout` must match the alignment used
730     ///   to allocate that block of memory.
731     unsafe fn dealloc(&mut self, ptr: NonNull<u8>, layout: Layout);
732
733     // == ALLOCATOR-SPECIFIC QUANTITIES AND LIMITS ==
734     // usable_size
735
736     /// Returns bounds on the guaranteed usable size of a successful
737     /// allocation created with the specified `layout`.
738     ///
739     /// In particular, if one has a memory block allocated via a given
740     /// allocator `a` and layout `k` where `a.usable_size(k)` returns
741     /// `(l, u)`, then one can pass that block to `a.dealloc()` with a
742     /// layout in the size range [l, u].
743     ///
744     /// (All implementors of `usable_size` must ensure that
745     /// `l <= k.size() <= u`)
746     ///
747     /// Both the lower- and upper-bounds (`l` and `u` respectively)
748     /// are provided, because an allocator based on size classes could
749     /// misbehave if one attempts to deallocate a block without
750     /// providing a correct value for its size (i.e., one within the
751     /// range `[l, u]`).
752     ///
753     /// Clients who wish to make use of excess capacity are encouraged
754     /// to use the `alloc_excess` and `realloc_excess` instead, as
755     /// this method is constrained to report conservative values that
756     /// serve as valid bounds for *all possible* allocation method
757     /// calls.
758     ///
759     /// However, for clients that do not wish to track the capacity
760     /// returned by `alloc_excess` locally, this method is likely to
761     /// produce useful results.
762     #[inline]
763     fn usable_size(&self, layout: &Layout) -> (usize, usize) {
764         (layout.size(), layout.size())
765     }
766
767     // == METHODS FOR MEMORY REUSE ==
768     // realloc. alloc_excess, realloc_excess
769
770     /// Returns a pointer suitable for holding data described by
771     /// a new layout with `layout`’s alignment and a size given
772     /// by `new_size`. To
773     /// accomplish this, this may extend or shrink the allocation
774     /// referenced by `ptr` to fit the new layout.
775     ///
776     /// If this returns `Ok`, then ownership of the memory block
777     /// referenced by `ptr` has been transferred to this
778     /// allocator. The memory may or may not have been freed, and
779     /// should be considered unusable (unless of course it was
780     /// transferred back to the caller again via the return value of
781     /// this method).
782     ///
783     /// If this method returns `Err`, then ownership of the memory
784     /// block has not been transferred to this allocator, and the
785     /// contents of the memory block are unaltered.
786     ///
787     /// # Safety
788     ///
789     /// This function is unsafe because undefined behavior can result
790     /// if the caller does not ensure all of the following:
791     ///
792     /// * `ptr` must be currently allocated via this allocator,
793     ///
794     /// * `layout` must *fit* the `ptr` (see above). (The `new_size`
795     ///   argument need not fit it.)
796     ///
797     /// * `new_size` must be greater than zero.
798     ///
799     /// * `new_size`, when rounded up to the nearest multiple of `layout.align()`,
800     ///   must not overflow (i.e., the rounded value must be less than `usize::MAX`).
801     ///
802     /// (Extension subtraits might provide more specific bounds on
803     /// behavior, e.g., guarantee a sentinel address or a null pointer
804     /// in response to a zero-size allocation request.)
805     ///
806     /// # Errors
807     ///
808     /// Returns `Err` only if the new layout
809     /// does not meet the allocator's size
810     /// and alignment constraints of the allocator, or if reallocation
811     /// otherwise fails.
812     ///
813     /// Implementations are encouraged to return `Err` on memory
814     /// exhaustion rather than panicking or aborting, but this is not
815     /// a strict requirement. (Specifically: it is *legal* to
816     /// implement this trait atop an underlying native allocation
817     /// library that aborts on memory exhaustion.)
818     ///
819     /// Clients wishing to abort computation in response to a
820     /// reallocation error are encouraged to call the [`handle_alloc_error`] function,
821     /// rather than directly invoking `panic!` or similar.
822     ///
823     /// [`handle_alloc_error`]: ../../alloc/alloc/fn.handle_alloc_error.html
824     unsafe fn realloc(
825         &mut self,
826         ptr: NonNull<u8>,
827         layout: Layout,
828         new_size: usize,
829     ) -> Result<NonNull<u8>, AllocErr> {
830         let old_size = layout.size();
831
832         if new_size >= old_size {
833             if let Ok(()) = self.grow_in_place(ptr, layout, new_size) {
834                 return Ok(ptr);
835             }
836         } else if new_size < old_size {
837             if let Ok(()) = self.shrink_in_place(ptr, layout, new_size) {
838                 return Ok(ptr);
839             }
840         }
841
842         // otherwise, fall back on alloc + copy + dealloc.
843         let new_layout = Layout::from_size_align_unchecked(new_size, layout.align());
844         let result = self.alloc(new_layout);
845         if let Ok(new_ptr) = result {
846             ptr::copy_nonoverlapping(ptr.as_ptr(), new_ptr.as_ptr(), cmp::min(old_size, new_size));
847             self.dealloc(ptr, layout);
848         }
849         result
850     }
851
852     /// Behaves like `realloc`, but also ensures that the new contents
853     /// are set to zero before being returned.
854     ///
855     /// # Safety
856     ///
857     /// This function is unsafe for the same reasons that `realloc` is.
858     ///
859     /// # Errors
860     ///
861     /// Returns `Err` only if the new layout
862     /// does not meet the allocator's size
863     /// and alignment constraints of the allocator, or if reallocation
864     /// otherwise fails.
865     ///
866     /// Implementations are encouraged to return `Err` on memory
867     /// exhaustion rather than panicking or aborting, but this is not
868     /// a strict requirement. (Specifically: it is *legal* to
869     /// implement this trait atop an underlying native allocation
870     /// library that aborts on memory exhaustion.)
871     ///
872     /// Clients wishing to abort computation in response to a
873     /// reallocation error are encouraged to call the [`handle_alloc_error`] function,
874     /// rather than directly invoking `panic!` or similar.
875     ///
876     /// [`handle_alloc_error`]: ../../alloc/alloc/fn.handle_alloc_error.html
877     unsafe fn realloc_zeroed(
878         &mut self,
879         ptr: NonNull<u8>,
880         layout: Layout,
881         new_size: usize,
882     ) -> Result<NonNull<u8>, AllocErr> {
883         let old_size = layout.size();
884
885         if new_size >= old_size {
886             if let Ok(()) = self.grow_in_place_zeroed(ptr, layout, new_size) {
887                 return Ok(ptr);
888             }
889         } else if new_size < old_size {
890             if let Ok(()) = self.shrink_in_place(ptr, layout, new_size) {
891                 return Ok(ptr);
892             }
893         }
894
895         // otherwise, fall back on alloc + copy + dealloc.
896         let new_layout = Layout::from_size_align_unchecked(new_size, layout.align());
897         let result = self.alloc_zeroed(new_layout);
898         if let Ok(new_ptr) = result {
899             ptr::copy_nonoverlapping(ptr.as_ptr(), new_ptr.as_ptr(), cmp::min(old_size, new_size));
900             self.dealloc(ptr, layout);
901         }
902         result
903     }
904
905     /// Behaves like `alloc`, but also ensures that the contents
906     /// are set to zero before being returned.
907     ///
908     /// # Safety
909     ///
910     /// This function is unsafe for the same reasons that `alloc` is.
911     ///
912     /// # Errors
913     ///
914     /// Returning `Err` indicates that either memory is exhausted or
915     /// `layout` does not meet allocator's size or alignment
916     /// constraints, just as in `alloc`.
917     ///
918     /// Clients wishing to abort computation in response to an
919     /// allocation error are encouraged to call the [`handle_alloc_error`] function,
920     /// rather than directly invoking `panic!` or similar.
921     ///
922     /// [`handle_alloc_error`]: ../../alloc/alloc/fn.handle_alloc_error.html
923     unsafe fn alloc_zeroed(&mut self, layout: Layout) -> Result<NonNull<u8>, AllocErr> {
924         let size = layout.size();
925         let p = self.alloc(layout);
926         if let Ok(p) = p {
927             ptr::write_bytes(p.as_ptr(), 0, size);
928         }
929         p
930     }
931
932     /// Behaves like `alloc`, but also returns the whole size of
933     /// the returned block. For some `layout` inputs, like arrays, this
934     /// may include extra storage usable for additional data.
935     ///
936     /// # Safety
937     ///
938     /// This function is unsafe for the same reasons that `alloc` is.
939     ///
940     /// # Errors
941     ///
942     /// Returning `Err` indicates that either memory is exhausted or
943     /// `layout` does not meet allocator's size or alignment
944     /// constraints, just as in `alloc`.
945     ///
946     /// Clients wishing to abort computation in response to an
947     /// allocation error are encouraged to call the [`handle_alloc_error`] function,
948     /// rather than directly invoking `panic!` or similar.
949     ///
950     /// [`handle_alloc_error`]: ../../alloc/alloc/fn.handle_alloc_error.html
951     unsafe fn alloc_excess(&mut self, layout: Layout) -> Result<Excess, AllocErr> {
952         let usable_size = self.usable_size(&layout);
953         self.alloc(layout).map(|p| Excess(p, usable_size.1))
954     }
955
956     /// Behaves like `alloc`, but also returns the whole size of
957     /// the returned block. For some `layout` inputs, like arrays, this
958     /// may include extra storage usable for additional data.
959     /// Also it ensures that the contents are set to zero before being returned.
960     ///
961     /// # Safety
962     ///
963     /// This function is unsafe for the same reasons that `alloc` is.
964     ///
965     /// # Errors
966     ///
967     /// Returning `Err` indicates that either memory is exhausted or
968     /// `layout` does not meet allocator's size or alignment
969     /// constraints, just as in `alloc`.
970     ///
971     /// Clients wishing to abort computation in response to an
972     /// allocation error are encouraged to call the [`handle_alloc_error`] function,
973     /// rather than directly invoking `panic!` or similar.
974     ///
975     /// [`handle_alloc_error`]: ../../alloc/alloc/fn.handle_alloc_error.html
976     unsafe fn alloc_excess_zeroed(&mut self, layout: Layout) -> Result<Excess, AllocErr> {
977         let usable_size = self.usable_size(&layout);
978         self.alloc_zeroed(layout).map(|p| Excess(p, usable_size.1))
979     }
980
981     /// Behaves like `realloc`, but also returns the whole size of
982     /// the returned block. For some `layout` inputs, like arrays, this
983     /// may include extra storage usable for additional data.
984     ///
985     /// # Safety
986     ///
987     /// This function is unsafe for the same reasons that `realloc` is.
988     ///
989     /// # Errors
990     ///
991     /// Returning `Err` indicates that either memory is exhausted or
992     /// `layout` does not meet allocator's size or alignment
993     /// constraints, just as in `realloc`.
994     ///
995     /// Clients wishing to abort computation in response to a
996     /// reallocation error are encouraged to call the [`handle_alloc_error`] function,
997     /// rather than directly invoking `panic!` or similar.
998     ///
999     /// [`handle_alloc_error`]: ../../alloc/alloc/fn.handle_alloc_error.html
1000     unsafe fn realloc_excess(
1001         &mut self,
1002         ptr: NonNull<u8>,
1003         layout: Layout,
1004         new_size: usize,
1005     ) -> Result<Excess, AllocErr> {
1006         let new_layout = Layout::from_size_align_unchecked(new_size, layout.align());
1007         let usable_size = self.usable_size(&new_layout);
1008         self.realloc(ptr, layout, new_size).map(|p| Excess(p, usable_size.1))
1009     }
1010
1011     /// Behaves like `realloc`, but also returns the whole size of
1012     /// the returned block. For some `layout` inputs, like arrays, this
1013     /// may include extra storage usable for additional data.
1014     /// Also it ensures that the contents are set to zero before being returned.
1015     ///
1016     /// # Safety
1017     ///
1018     /// This function is unsafe for the same reasons that `realloc` is.
1019     ///
1020     /// # Errors
1021     ///
1022     /// Returning `Err` indicates that either memory is exhausted or
1023     /// `layout` does not meet allocator's size or alignment
1024     /// constraints, just as in `realloc`.
1025     ///
1026     /// Clients wishing to abort computation in response to a
1027     /// reallocation error are encouraged to call the [`handle_alloc_error`] function,
1028     /// rather than directly invoking `panic!` or similar.
1029     ///
1030     /// [`handle_alloc_error`]: ../../alloc/alloc/fn.handle_alloc_error.html
1031     unsafe fn realloc_excess_zeroed(
1032         &mut self,
1033         ptr: NonNull<u8>,
1034         layout: Layout,
1035         new_size: usize,
1036     ) -> Result<Excess, AllocErr> {
1037         let new_layout = Layout::from_size_align_unchecked(new_size, layout.align());
1038         let usable_size = self.usable_size(&new_layout);
1039         self.realloc_zeroed(ptr, layout, new_size).map(|p| Excess(p, usable_size.1))
1040     }
1041
1042     /// Attempts to extend the allocation referenced by `ptr` to fit `new_size`.
1043     ///
1044     /// If this returns `Ok`, then the allocator has asserted that the
1045     /// memory block referenced by `ptr` now fits `new_size`, and thus can
1046     /// be used to carry data of a layout of that size and same alignment as
1047     /// `layout`. (The allocator is allowed to
1048     /// expend effort to accomplish this, such as extending the memory block to
1049     /// include successor blocks, or virtual memory tricks.)
1050     ///
1051     /// Regardless of what this method returns, ownership of the
1052     /// memory block referenced by `ptr` has not been transferred, and
1053     /// the contents of the memory block are unaltered.
1054     ///
1055     /// # Safety
1056     ///
1057     /// This function is unsafe because undefined behavior can result
1058     /// if the caller does not ensure all of the following:
1059     ///
1060     /// * `ptr` must be currently allocated via this allocator,
1061     ///
1062     /// * `layout` must *fit* the `ptr` (see above); note the
1063     ///   `new_size` argument need not fit it,
1064     ///
1065     /// * `new_size` must not be less than `layout.size()`,
1066     ///
1067     /// # Errors
1068     ///
1069     /// Returns `Err(CannotReallocInPlace)` when the allocator is
1070     /// unable to assert that the memory block referenced by `ptr`
1071     /// could fit `layout`.
1072     ///
1073     /// Note that one cannot pass `CannotReallocInPlace` to the `handle_alloc_error`
1074     /// function; clients are expected either to be able to recover from
1075     /// `grow_in_place` failures without aborting, or to fall back on
1076     /// another reallocation method before resorting to an abort.
1077     unsafe fn grow_in_place(
1078         &mut self,
1079         ptr: NonNull<u8>,
1080         layout: Layout,
1081         new_size: usize,
1082     ) -> Result<(), CannotReallocInPlace> {
1083         let _ = ptr; // this default implementation doesn't care about the actual address.
1084         debug_assert!(new_size >= layout.size());
1085         let (_l, u) = self.usable_size(&layout);
1086         // _l <= layout.size()                       [guaranteed by usable_size()]
1087         //       layout.size() <= new_layout.size()  [required by this method]
1088         if new_size <= u { Ok(()) } else { Err(CannotReallocInPlace) }
1089     }
1090
1091     /// Behaves like `grow_in_place`, but also ensures that the new
1092     /// contents are set to zero before being returned.
1093     ///
1094     /// # Safety
1095     ///
1096     /// This function is unsafe for the same reasons that `grow_in_place` is.
1097     ///
1098     /// # Errors
1099     ///
1100     /// Returns `Err(CannotReallocInPlace)` when the allocator is
1101     /// unable to assert that the memory block referenced by `ptr`
1102     /// could fit `layout`.
1103     ///
1104     /// Note that one cannot pass `CannotReallocInPlace` to the `handle_alloc_error`
1105     /// function; clients are expected either to be able to recover from
1106     /// `grow_in_place` failures without aborting, or to fall back on
1107     /// another reallocation method before resorting to an abort.
1108     unsafe fn grow_in_place_zeroed(
1109         &mut self,
1110         ptr: NonNull<u8>,
1111         layout: Layout,
1112         new_size: usize,
1113     ) -> Result<(), CannotReallocInPlace> {
1114         self.grow_in_place(ptr, layout, new_size)?;
1115         ptr.as_ptr().add(layout.size()).write_bytes(0, new_size - layout.size());
1116         Ok(())
1117     }
1118
1119     /// Attempts to shrink the allocation referenced by `ptr` to fit `new_size`.
1120     ///
1121     /// If this returns `Ok`, then the allocator has asserted that the
1122     /// memory block referenced by `ptr` now fits `new_size`, and
1123     /// thus can only be used to carry data of that smaller
1124     /// layout. (The allocator is allowed to take advantage of this,
1125     /// carving off portions of the block for reuse elsewhere.) The
1126     /// truncated contents of the block within the smaller layout are
1127     /// unaltered, and ownership of block has not been transferred.
1128     ///
1129     /// If this returns `Err`, then the memory block is considered to
1130     /// still represent the original (larger) `layout`. None of the
1131     /// block has been carved off for reuse elsewhere, ownership of
1132     /// the memory block has not been transferred, and the contents of
1133     /// the memory block are unaltered.
1134     ///
1135     /// # Safety
1136     ///
1137     /// This function is unsafe because undefined behavior can result
1138     /// if the caller does not ensure all of the following:
1139     ///
1140     /// * `ptr` must be currently allocated via this allocator,
1141     ///
1142     /// * `layout` must *fit* the `ptr` (see above); note the
1143     ///   `new_size` argument need not fit it,
1144     ///
1145     /// * `new_size` must not be greater than `layout.size()`
1146     ///   (and must be greater than zero),
1147     ///
1148     /// # Errors
1149     ///
1150     /// Returns `Err(CannotReallocInPlace)` when the allocator is
1151     /// unable to assert that the memory block referenced by `ptr`
1152     /// could fit `layout`.
1153     ///
1154     /// Note that one cannot pass `CannotReallocInPlace` to the `handle_alloc_error`
1155     /// function; clients are expected either to be able to recover from
1156     /// `shrink_in_place` failures without aborting, or to fall back
1157     /// on another reallocation method before resorting to an abort.
1158     unsafe fn shrink_in_place(
1159         &mut self,
1160         ptr: NonNull<u8>,
1161         layout: Layout,
1162         new_size: usize,
1163     ) -> Result<(), CannotReallocInPlace> {
1164         let _ = ptr; // this default implementation doesn't care about the actual address.
1165         debug_assert!(new_size <= layout.size());
1166         let (l, _u) = self.usable_size(&layout);
1167         //                      layout.size() <= _u  [guaranteed by usable_size()]
1168         // new_layout.size() <= layout.size()        [required by this method]
1169         if l <= new_size { Ok(()) } else { Err(CannotReallocInPlace) }
1170     }
1171 }