Skip to main content

core/alloc/
mod.rs

1//! Memory allocation APIs
2
3#![stable(feature = "alloc_module", since = "1.28.0")]
4
5mod global;
6mod layout;
7
8#[stable(feature = "global_alloc", since = "1.28.0")]
9pub use self::global::GlobalAlloc;
10#[stable(feature = "alloc_layout", since = "1.28.0")]
11pub use self::layout::Layout;
12#[stable(feature = "alloc_layout", since = "1.28.0")]
13#[deprecated(
14    since = "1.52.0",
15    note = "Name does not follow std convention, use LayoutError",
16    suggestion = "LayoutError"
17)]
18#[allow(deprecated, deprecated_in_future)]
19pub use self::layout::LayoutErr;
20#[stable(feature = "alloc_layout_error", since = "1.50.0")]
21pub use self::layout::LayoutError;
22use crate::error::Error;
23use crate::fmt;
24use crate::ptr::{self, NonNull};
25
26/// The `AllocError` error indicates an allocation failure
27/// that may be due to resource exhaustion or to
28/// something wrong when combining the given input arguments with this
29/// allocator.
30#[unstable(feature = "allocator_api", issue = "32838")]
31#[derive(Copy, Clone, PartialEq, Eq, Debug)]
32pub struct AllocError;
33
34#[unstable(
35    feature = "allocator_api",
36    reason = "the precise API and guarantees it provides may be tweaked.",
37    issue = "32838"
38)]
39impl Error for AllocError {}
40
41// (we need this for downstream impl of trait Error)
42#[unstable(feature = "allocator_api", issue = "32838")]
43impl fmt::Display for AllocError {
44    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
45        f.write_str("memory allocation failed")
46    }
47}
48
49/// An implementation of `Allocator` can allocate, grow, shrink, and deallocate arbitrary blocks of
50/// data described via [`Layout`][].
51///
52/// `Allocator` is designed to be implemented on ZSTs, references, or smart pointers.
53/// An allocator for `MyAlloc([u8; N])` cannot be moved, without updating the pointers to the
54/// allocated memory.
55///
56/// In contrast to [`GlobalAlloc`][], `Allocator` allows zero-sized allocations. If an underlying
57/// allocator does not support this (like jemalloc) or responds by returning a null pointer
58/// (such as `libc::malloc`), this must be caught by the implementation.
59///
60/// ### Equivalent allocators
61///
62/// Multiple allocator values can sometimes be interchangeable with each other.
63/// When this is the case, we refer to those allocators as being *equivalent* to
64/// each other.
65///
66/// The following conditions are sufficient conditions for allocators to be equivalent.
67/// * An allocator is equivalent to itself. (Equivalence is reflexive.)
68/// * If an allocator is equivalent to a second allocator, then
69///   the second allocator is also equivalent to the first. (Equivalence is symmetric.)
70/// * If an allocator is equivalent to a second allocator, and
71///   the second allocator is equivalent to a third allocator, then
72///   the first allocator is also equivalent to the third allocator.
73///   (Equivalence is transitive.)
74/// * Moving, subtyping, unsize-coercing, or trait-upcasting an allocator does not change
75///   what the allocator is equivalent to.
76/// * Copying or cloning allocator results in an allocator that's
77///   equivalent to the initial allocator.
78///
79/// Additionally, implementors of `Allocator` may specify additional equivalences
80/// between allocators. It is the responsibility of such implementors to make sure
81/// that equivalent allocators have "compatible" `Allocator` implementations.
82/// In particular, the standard library specifies the following equivalences:
83/// * A reference to an allocator (either `&` or `&mut`) is equivalent to
84///   the allocator being referenced.
85/// * A `Box`, `Rc`, or `Arc` containing an allocator is equivalent to
86///   the allocator inside.
87/// * All `Global` allocator instances are equivalent with each other.
88/// * All `System` allocator instances are equivalent with each other.
89///
90/// Note: Currently, the interaction between cloning and unsize-coercing allocators
91/// is unsound, and there is ongoing discussion on how to revise the `Allocator` trait
92/// to fix this. See [#156920].
93///
94/// [#156920]: https://github.com/rust-lang/rust/issues/156920
95///
96/// ### Currently allocated memory
97///
98/// Some of the methods require that a memory block is *currently allocated* by some specific allocator.
99/// This means that:
100/// * the starting address for that memory block was previously returned by
101///   the [`allocate`], [`allocate_zeroed`], [`grow`], [`grow_zeroed`], or [`shrink`] methods,
102///   called on an allocator that's equivalent to this specific allocator; and
103/// * the memory block has not subsequently been [*invalidated*].
104///
105/// [*invalidated*]: #invalidating-memory-blocks
106///
107/// ### Invalidating memory blocks
108///
109/// A memory block that is currently allocated becomes *invalidated* when one
110/// of the following happens:
111/// * The memory block is deallocated. This occurs when the memory block
112///   is passed as an argument to a [`deallocate`] call, or when it is passed
113///   as an argument to a [`grow`], [`grow_zeroed`] or [`shrink`] call that returns `Ok`.
114/// * All (equivalent) allocators that this memory block is allocated with,
115///   each has one of the following happen to them:
116///   * The allocator's destructor runs.
117///   * The allocator is mutated through public API taking `&mut` access.
118///   * One of the borrow-checker lifetimes in the allocator's type expires.
119///
120/// Note that these conditions imply that a collection may ensure that
121/// any specific currently allocated memory block won't be invalidated, by:
122/// * not deallocating that memory block,
123/// * owning an allocator that memory block is allocated with, and
124/// * not publicly exposing `&mut` access to that allocator.
125///
126/// Also note that safe public API of an allocator with `&` access is not
127/// allowed to invalidate its memory blocks. Furthermore, unsafe public API
128/// of an allocator with `&` access must document that they invalidate
129/// memory blocks (e.g., by calling `deallocate`) if they do. Therefore,
130/// collections may safely expose `&` access to its allocator.
131///
132/// Also note that, even in cases where are other "alive" allocators known to be
133/// equivalent to a given collection's allocator, most collections still should
134/// not publicly expose `&mut` access to its allocator. The fact that there are
135/// other "alive" allocators would prevent this `&mut` access from invalidating
136/// the collection's memory block, but public `&mut` access is still likely to
137/// be unsound, since a user could replace the collection's allocator with
138/// a non-equivalent allocator, causing the collection to deallocate its memory
139/// with the wrong allocator.
140///
141/// [`allocate`]: Allocator::allocate
142/// [`allocate_zeroed`]: Allocator::allocate_zeroed
143/// [`grow`]: Allocator::grow
144/// [`grow_zeroed`]: Allocator::grow_zeroed
145/// [`shrink`]: Allocator::shrink
146/// [`deallocate`]: Allocator::deallocate
147///
148/// ### Memory fitting
149///
150/// Some of the methods require that a `layout` *fit* a memory block or vice versa. This means that the
151/// following conditions must hold:
152///  * the memory block must be *currently allocated* with alignment of [`layout.align()`], and
153///  * [`layout.size()`] must fall in the range `min ..= max`, where:
154///    - `min` is the size of the layout used to allocate the block, and
155///    - `max` is the actual size returned from [`allocate`], [`allocate_zeroed`],
156///      [`grow`], [`grow_zeroed`], or [`shrink`].
157///
158/// [`layout.align()`]: Layout::align
159/// [`layout.size()`]: Layout::size
160///
161/// # Safety
162///
163/// Implementors of `Allocator` must ensure that a memory block that
164/// is [*currently allocated*] by the allocator points to valid memory,
165/// until that memory block is [*invalidated*]. The implementor must also
166/// not violate this invariant of `Allocator` via allocator equivalences
167/// that are in the implementor's control (e.g., via a misbehaving
168/// `impl Clone for Box<MyAllocator>`).
169///
170/// Additionally, any memory block returned by the allocator must
171/// satisfy the allocation invariants described in `core::ptr`.
172/// In particular, if a block has base address `p` and size `n`,
173/// then `p as usize + n <= usize::MAX` must hold.
174///
175/// This ensures that pointer arithmetic within the allocation
176/// (for example, `ptr.add(len)`) cannot overflow the address space.
177///
178/// [*currently allocated*]: #currently-allocated-memory
179/// [*invalidated*]: #invalidating-memory-blocks
180#[unstable(feature = "allocator_api", issue = "32838")]
181#[rustc_const_unstable(feature = "const_heap", issue = "79597")]
182pub const unsafe trait Allocator {
183    /// Attempts to allocate a block of memory.
184    ///
185    /// On success, returns a [`NonNull<[u8]>`][NonNull] meeting the size and alignment guarantees of `layout`.
186    ///
187    /// The returned block may have a larger size than specified by `layout.size()`, and may or may
188    /// not have its contents initialized.
189    ///
190    /// Note that the returned block of memory is considered [*currently allocated*]
191    /// with this allocator (and equivalent allocators).
192    /// Therefore, it is the responsibility of implementors of `Allocator` to make sure that
193    /// this block of memory points to valid memory until the block is [*invalidated*]
194    ///
195    /// [*currently allocated*]: #currently-allocated-memory
196    /// [*invalidated*]: #invalidating-memory-blocks
197    ///
198    /// # Errors
199    ///
200    /// Returning `Err` indicates that either memory is exhausted or `layout` does not meet
201    /// allocator's size or alignment constraints.
202    ///
203    /// Implementations are encouraged to return `Err` on memory exhaustion rather than panicking or
204    /// aborting, but this is not a strict requirement. (Specifically: it is *legal* to implement
205    /// this trait atop an underlying native allocation library that aborts on memory exhaustion.)
206    ///
207    /// Clients wishing to abort computation in response to an allocation error are encouraged to
208    /// call the [`handle_alloc_error`] function, rather than directly invoking `panic!` or similar.
209    ///
210    /// [`handle_alloc_error`]: ../../alloc/alloc/fn.handle_alloc_error.html
211    fn allocate(&self, layout: Layout) -> Result<NonNull<[u8]>, AllocError>;
212
213    /// Behaves like `allocate`, but also ensures that the returned memory is zero-initialized.
214    ///
215    /// # Errors
216    ///
217    /// Returning `Err` indicates that either memory is exhausted or `layout` does not meet
218    /// allocator's size or alignment constraints.
219    ///
220    /// Implementations are encouraged to return `Err` on memory exhaustion rather than panicking or
221    /// aborting, but this is not a strict requirement. (Specifically: it is *legal* to implement
222    /// this trait atop an underlying native allocation library that aborts on memory exhaustion.)
223    ///
224    /// Clients wishing to abort computation in response to an allocation error are encouraged to
225    /// call the [`handle_alloc_error`] function, rather than directly invoking `panic!` or similar.
226    ///
227    /// [`handle_alloc_error`]: ../../alloc/alloc/fn.handle_alloc_error.html
228    fn allocate_zeroed(&self, layout: Layout) -> Result<NonNull<[u8]>, AllocError> {
229        let ptr = self.allocate(layout)?;
230        // SAFETY: `alloc` returns a valid memory block
231        unsafe { ptr.as_non_null_ptr().as_ptr().write_bytes(0, ptr.len()) }
232        Ok(ptr)
233    }
234
235    /// Deallocates the memory referenced by `ptr`.
236    ///
237    /// # Safety
238    ///
239    /// * `ptr` must denote a block of memory [*currently allocated*] via this allocator, and
240    /// * `layout` must [*fit*] that block of memory.
241    ///
242    /// [*currently allocated*]: #currently-allocated-memory
243    /// [*fit*]: #memory-fitting
244    unsafe fn deallocate(&self, ptr: NonNull<u8>, layout: Layout);
245
246    /// Attempts to extend the memory block.
247    ///
248    /// Returns a new [`NonNull<[u8]>`][NonNull] containing a pointer and the actual size of the allocated
249    /// memory. The pointer is suitable for holding data described by `new_layout`. To accomplish
250    /// this, the allocator may extend the allocation referenced by `ptr` to fit the new layout.
251    ///
252    /// If this returns `Ok`, then the memory block referenced by `ptr` has been [*invalidated*].
253    /// The old `ptr` must not be used to access the memory, even if the allocation was grown in-place.
254    /// The newly returned pointer is the only valid pointer for accessing this memory now.
255    ///
256    /// If this method returns `Err`, then the memory block has not been *invalidated*,
257    /// and the contents of the memory block are unaltered.
258    ///
259    /// # Safety
260    ///
261    /// * `ptr` must denote a block of memory [*currently allocated*] via this allocator.
262    /// * `old_layout` must [*fit*] that block of memory (The `new_layout` argument need not fit it.).
263    /// * `new_layout.size()` must be greater than or equal to `old_layout.size()`.
264    ///
265    /// Note that `new_layout.align()` need not be the same as `old_layout.align()`.
266    ///
267    /// [*currently allocated*]: #currently-allocated-memory
268    /// [*fit*]: #memory-fitting
269    /// [*invalidated*]: #invalidating-memory-blocks
270    ///
271    /// # Errors
272    ///
273    /// Returns `Err` if the new layout does not meet the allocator's size and alignment
274    /// constraints of the allocator, or if growing otherwise fails.
275    ///
276    /// Implementations are encouraged to return `Err` on memory exhaustion rather than panicking or
277    /// aborting, but this is not a strict requirement. (Specifically: it is *legal* to implement
278    /// this trait atop an underlying native allocation library that aborts on memory exhaustion.)
279    ///
280    /// Clients wishing to abort computation in response to an allocation error are encouraged to
281    /// call the [`handle_alloc_error`] function, rather than directly invoking `panic!` or similar.
282    ///
283    /// [`handle_alloc_error`]: ../../alloc/alloc/fn.handle_alloc_error.html
284    unsafe fn grow(
285        &self,
286        ptr: NonNull<u8>,
287        old_layout: Layout,
288        new_layout: Layout,
289    ) -> Result<NonNull<[u8]>, AllocError> {
290        debug_assert!(
291            new_layout.size() >= old_layout.size(),
292            "`new_layout.size()` must be greater than or equal to `old_layout.size()`"
293        );
294
295        let new_ptr = self.allocate(new_layout)?;
296
297        // SAFETY: because `new_layout.size()` must be greater than or equal to
298        // `old_layout.size()`, both the old and new memory allocation are valid for reads and
299        // writes for `old_layout.size()` bytes. Also, because the old allocation wasn't yet
300        // deallocated, it cannot overlap `new_ptr`. Thus, the call to `copy_nonoverlapping` is
301        // safe. The safety contract for `dealloc` must be upheld by the caller.
302        unsafe {
303            ptr::copy_nonoverlapping(ptr.as_ptr(), new_ptr.as_mut_ptr(), old_layout.size());
304            self.deallocate(ptr, old_layout);
305        }
306
307        Ok(new_ptr)
308    }
309
310    /// Behaves like `grow`, but also ensures that the new contents are set to zero before being
311    /// returned.
312    ///
313    /// The memory block will contain the following contents after a successful call to
314    /// `grow_zeroed`:
315    ///   * Bytes `0..old_layout.size()` are preserved from the original allocation.
316    ///   * Bytes `old_layout.size()..old_size` will either be preserved or zeroed, depending on
317    ///     the allocator implementation. `old_size` refers to the size of the memory block prior
318    ///     to the `grow_zeroed` call, which may be larger than the size that was originally
319    ///     requested when it was allocated.
320    ///   * Bytes `old_size..new_size` are zeroed. `new_size` refers to the size of the memory
321    ///     block returned by the `grow_zeroed` call.
322    ///
323    /// # Safety
324    ///
325    /// * `ptr` must denote a block of memory [*currently allocated*] via this allocator.
326    /// * `old_layout` must [*fit*] that block of memory (The `new_layout` argument need not fit it.).
327    /// * `new_layout.size()` must be greater than or equal to `old_layout.size()`.
328    ///
329    /// Note that `new_layout.align()` need not be the same as `old_layout.align()`.
330    ///
331    /// [*currently allocated*]: #currently-allocated-memory
332    /// [*fit*]: #memory-fitting
333    ///
334    /// # Errors
335    ///
336    /// Returns `Err` if the new layout does not meet the allocator's size and alignment
337    /// constraints of the allocator, or if growing otherwise fails.
338    ///
339    /// Implementations are encouraged to return `Err` on memory exhaustion rather than panicking or
340    /// aborting, but this is not a strict requirement. (Specifically: it is *legal* to implement
341    /// this trait atop an underlying native allocation library that aborts on memory exhaustion.)
342    ///
343    /// Clients wishing to abort computation in response to an allocation error are encouraged to
344    /// call the [`handle_alloc_error`] function, rather than directly invoking `panic!` or similar.
345    ///
346    /// [`handle_alloc_error`]: ../../alloc/alloc/fn.handle_alloc_error.html
347    unsafe fn grow_zeroed(
348        &self,
349        ptr: NonNull<u8>,
350        old_layout: Layout,
351        new_layout: Layout,
352    ) -> Result<NonNull<[u8]>, AllocError> {
353        debug_assert!(
354            new_layout.size() >= old_layout.size(),
355            "`new_layout.size()` must be greater than or equal to `old_layout.size()`"
356        );
357
358        let new_ptr = self.allocate_zeroed(new_layout)?;
359
360        // SAFETY: because `new_layout.size()` must be greater than or equal to
361        // `old_layout.size()`, both the old and new memory allocation are valid for reads and
362        // writes for `old_layout.size()` bytes. Also, because the old allocation wasn't yet
363        // deallocated, it cannot overlap `new_ptr`. Thus, the call to `copy_nonoverlapping` is
364        // safe. The safety contract for `dealloc` must be upheld by the caller.
365        unsafe {
366            ptr::copy_nonoverlapping(ptr.as_ptr(), new_ptr.as_mut_ptr(), old_layout.size());
367            self.deallocate(ptr, old_layout);
368        }
369
370        Ok(new_ptr)
371    }
372
373    /// Attempts to shrink the memory block.
374    ///
375    /// Returns a new [`NonNull<[u8]>`][NonNull] containing a pointer and the actual size of the allocated
376    /// memory. The pointer is suitable for holding data described by `new_layout`. To accomplish
377    /// this, the allocator may shrink the allocation referenced by `ptr` to fit the new layout.
378    ///
379    ///
380    /// If this returns `Ok`, then the memory block referenced by `ptr` has been [*invalidated*].
381    /// The old `ptr` must not be used to access the memory, even if the allocation was shrunk in-place.
382    /// The newly returned pointer is the only valid pointer for accessing this memory now.
383    ///
384    /// If this method returns `Err`, then the memory block has not been *invalidated*,
385    /// and the contents of the memory block are unaltered.
386    ///
387    /// # Safety
388    ///
389    /// * `ptr` must denote a block of memory [*currently allocated*] via this allocator.
390    /// * `old_layout` must [*fit*] that block of memory (The `new_layout` argument need not fit it.).
391    /// * `new_layout.size()` must be smaller than or equal to `old_layout.size()`.
392    ///
393    /// Note that `new_layout.align()` need not be the same as `old_layout.align()`.
394    ///
395    /// [*currently allocated*]: #currently-allocated-memory
396    /// [*fit*]: #memory-fitting
397    /// [*invalidated*]: #invalidating-memory-blocks
398    ///
399    /// # Errors
400    ///
401    /// Returns `Err` if the new layout does not meet the allocator's size and alignment
402    /// constraints of the allocator, or if shrinking otherwise fails.
403    ///
404    /// Implementations are encouraged to return `Err` on memory exhaustion rather than panicking or
405    /// aborting, but this is not a strict requirement. (Specifically: it is *legal* to implement
406    /// this trait atop an underlying native allocation library that aborts on memory exhaustion.)
407    ///
408    /// Clients wishing to abort computation in response to an allocation error are encouraged to
409    /// call the [`handle_alloc_error`] function, rather than directly invoking `panic!` or similar.
410    ///
411    /// [`handle_alloc_error`]: ../../alloc/alloc/fn.handle_alloc_error.html
412    unsafe fn shrink(
413        &self,
414        ptr: NonNull<u8>,
415        old_layout: Layout,
416        new_layout: Layout,
417    ) -> Result<NonNull<[u8]>, AllocError> {
418        debug_assert!(
419            new_layout.size() <= old_layout.size(),
420            "`new_layout.size()` must be smaller than or equal to `old_layout.size()`"
421        );
422
423        let new_ptr = self.allocate(new_layout)?;
424
425        // SAFETY: because `new_layout.size()` must be lower than or equal to
426        // `old_layout.size()`, both the old and new memory allocation are valid for reads and
427        // writes for `new_layout.size()` bytes. Also, because the old allocation wasn't yet
428        // deallocated, it cannot overlap `new_ptr`. Thus, the call to `copy_nonoverlapping` is
429        // safe. The safety contract for `dealloc` must be upheld by the caller.
430        unsafe {
431            ptr::copy_nonoverlapping(ptr.as_ptr(), new_ptr.as_mut_ptr(), new_layout.size());
432            self.deallocate(ptr, old_layout);
433        }
434
435        Ok(new_ptr)
436    }
437
438    /// Creates a "by reference" adapter for this instance of `Allocator`.
439    ///
440    /// The returned adapter also implements `Allocator` and will simply borrow this.
441    #[inline(always)]
442    fn by_ref(&self) -> &Self
443    where
444        Self: Sized,
445    {
446        self
447    }
448}
449
450#[unstable(feature = "allocator_api", issue = "32838")]
451#[rustc_const_unstable(feature = "const_heap", issue = "79597")]
452const unsafe impl<A> Allocator for &A
453where
454    A: [const] Allocator + ?Sized,
455{
456    #[inline]
457    fn allocate(&self, layout: Layout) -> Result<NonNull<[u8]>, AllocError> {
458        (**self).allocate(layout)
459    }
460
461    #[inline]
462    fn allocate_zeroed(&self, layout: Layout) -> Result<NonNull<[u8]>, AllocError> {
463        (**self).allocate_zeroed(layout)
464    }
465
466    #[inline]
467    unsafe fn deallocate(&self, ptr: NonNull<u8>, layout: Layout) {
468        // SAFETY: the safety contract must be upheld by the caller
469        unsafe { (**self).deallocate(ptr, layout) }
470    }
471
472    #[inline]
473    unsafe fn grow(
474        &self,
475        ptr: NonNull<u8>,
476        old_layout: Layout,
477        new_layout: Layout,
478    ) -> Result<NonNull<[u8]>, AllocError> {
479        // SAFETY: the safety contract must be upheld by the caller
480        unsafe { (**self).grow(ptr, old_layout, new_layout) }
481    }
482
483    #[inline]
484    unsafe fn grow_zeroed(
485        &self,
486        ptr: NonNull<u8>,
487        old_layout: Layout,
488        new_layout: Layout,
489    ) -> Result<NonNull<[u8]>, AllocError> {
490        // SAFETY: the safety contract must be upheld by the caller
491        unsafe { (**self).grow_zeroed(ptr, old_layout, new_layout) }
492    }
493
494    #[inline]
495    unsafe fn shrink(
496        &self,
497        ptr: NonNull<u8>,
498        old_layout: Layout,
499        new_layout: Layout,
500    ) -> Result<NonNull<[u8]>, AllocError> {
501        // SAFETY: the safety contract must be upheld by the caller
502        unsafe { (**self).shrink(ptr, old_layout, new_layout) }
503    }
504}
505
506#[unstable(feature = "allocator_api", issue = "32838")]
507unsafe impl<A> Allocator for &mut A
508where
509    A: Allocator + ?Sized,
510{
511    #[inline]
512    fn allocate(&self, layout: Layout) -> Result<NonNull<[u8]>, AllocError> {
513        (**self).allocate(layout)
514    }
515
516    #[inline]
517    fn allocate_zeroed(&self, layout: Layout) -> Result<NonNull<[u8]>, AllocError> {
518        (**self).allocate_zeroed(layout)
519    }
520
521    #[inline]
522    unsafe fn deallocate(&self, ptr: NonNull<u8>, layout: Layout) {
523        // SAFETY: the safety contract must be upheld by the caller
524        unsafe { (**self).deallocate(ptr, layout) }
525    }
526
527    #[inline]
528    unsafe fn grow(
529        &self,
530        ptr: NonNull<u8>,
531        old_layout: Layout,
532        new_layout: Layout,
533    ) -> Result<NonNull<[u8]>, AllocError> {
534        // SAFETY: the safety contract must be upheld by the caller
535        unsafe { (**self).grow(ptr, old_layout, new_layout) }
536    }
537
538    #[inline]
539    unsafe fn grow_zeroed(
540        &self,
541        ptr: NonNull<u8>,
542        old_layout: Layout,
543        new_layout: Layout,
544    ) -> Result<NonNull<[u8]>, AllocError> {
545        // SAFETY: the safety contract must be upheld by the caller
546        unsafe { (**self).grow_zeroed(ptr, old_layout, new_layout) }
547    }
548
549    #[inline]
550    unsafe fn shrink(
551        &self,
552        ptr: NonNull<u8>,
553        old_layout: Layout,
554        new_layout: Layout,
555    ) -> Result<NonNull<[u8]>, AllocError> {
556        // SAFETY: the safety contract must be upheld by the caller
557        unsafe { (**self).shrink(ptr, old_layout, new_layout) }
558    }
559}