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)]
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#[stable(feature = "allocator_api", since = "1.100.0")]
31#[derive(Copy, Clone, PartialEq, Eq, Debug)]
32pub struct AllocError;
33
34#[stable(feature = "allocator_api", since = "1.100.0")]
35impl Error for AllocError {}
36
37// (we need this for downstream impl of trait Error)
38#[stable(feature = "allocator_api", since = "1.100.0")]
39impl fmt::Display for AllocError {
40    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
41        f.write_str("memory allocation failed")
42    }
43}
44
45/// An implementation of `Allocator` can allocate, grow, shrink, and deallocate arbitrary blocks of
46/// data described via [`Layout`][].
47///
48/// `Allocator` is mostly designed to be implemented on ZSTs, references, or smart pointers,
49/// but can also be implemented directly on the underlying memory-owning type so long as it
50/// upholds the necessary guarantees. In general, an allocator of the type `MyAlloc([u8; N])`
51/// cannot be soundly created without being pinned or otherwise immovable in order to be
52/// correct.
53///
54/// In contrast to [`GlobalAlloc`][], `Allocator` allows zero-sized allocations. If an underlying
55/// allocator does not support this (like jemalloc) or responds by returning a null pointer
56/// (such as `libc::malloc`), this must be caught by the implementation.
57///
58/// # Examples
59///
60/// Sample that keeps track of the number of existing allocations:
61///
62/// ```
63/// use std::alloc::{AllocError, Allocator, Layout, System};
64/// use std::ptr::NonNull;
65/// use std::sync::atomic::{AtomicUsize, Ordering};
66///
67/// static LIVE_ALLOCATIONS: AtomicUsize = AtomicUsize::new(0);
68///
69/// struct CountingAllocator;
70///
71/// unsafe impl Allocator for CountingAllocator {
72///     fn allocate(&self, layout: Layout) -> Result<NonNull<[u8]>, AllocError> {
73///         let ptr = System.allocate(layout)?;
74///         LIVE_ALLOCATIONS.fetch_add(1, Ordering::Relaxed);
75///         Ok(ptr)
76///     }
77///
78///     unsafe fn deallocate(&self, ptr: NonNull<u8>, layout: Layout) {
79///         // SAFETY: the caller guarantees `ptr` was allocated by this allocator with `layout`,
80///         // and every block from this allocator was allocated by `System` with the same layout.
81///         unsafe { System.deallocate(ptr, layout) };
82///         LIVE_ALLOCATIONS.fetch_sub(1, Ordering::Relaxed);
83///     }
84/// }
85///
86/// // The Box allocates through our allocator.
87/// let new_box = Box::new_in(10, CountingAllocator);
88/// assert_eq!(LIVE_ALLOCATIONS.load(Ordering::Relaxed), 1);
89/// drop(new_box);
90/// assert_eq!(LIVE_ALLOCATIONS.load(Ordering::Relaxed), 0);
91/// ```
92///
93/// ## Implementation Requirements
94///
95/// In order to be usable in a flexible manner while still being sound, implementors of the trait
96/// must uphold very detailed semantics as explained below; the following terms are thus provided
97/// as vocabulary for allocator safety and implementation requirements:
98///
99/// ### Equivalent allocators
100///
101/// Multiple allocator values can sometimes be interchangeable with each other.
102/// When this is the case, we refer to those allocators as being *equivalent* to
103/// each other.
104///
105/// Users of allocators may assume the following are true of equivalent allocators,
106/// and implementors must ensure these rules are upheld:
107/// * An allocator is equivalent to itself. (Equivalence is reflexive.)
108/// * If an allocator is equivalent to a second allocator, then
109///   the second allocator is also equivalent to the first. (Equivalence is symmetric.)
110/// * If an allocator is equivalent to a second allocator, and
111///   the second allocator is equivalent to a third allocator, then
112///   the first allocator is also equivalent to the third allocator.
113///   (Equivalence is transitive.)
114/// * Moving, subtyping, unsize-coercing, or trait-upcasting an allocator does not change
115///   what the allocator is equivalent to.
116/// * Copying or cloning an allocator creates an equivalent one, should the
117///   [`AllocatorClone`] trait be implemented.
118///
119/// Additionally, implementors of `Allocator` may specify additional equivalences
120/// between allocators. It is the responsibility of such implementors to make sure
121/// that equivalent allocators have "compatible" `Allocator` implementations.
122/// In particular, the standard library specifies the following equivalences:
123/// * A reference to an allocator (either `&` or `&mut`) is equivalent to
124///   the allocator being referenced.
125/// * A `Box`, `Rc`, or `Arc` containing an allocator is equivalent to
126///   the allocator inside.
127/// * All `Global` allocator instances are equivalent with each other.
128/// * All `System` allocator instances are equivalent with each other.
129///
130/// ### Currently allocated memory
131///
132/// Some of the methods require that a memory block is *currently allocated* by some specific allocator.
133/// This means that:
134/// * the starting address for that memory block was previously returned by
135///   the [`allocate`], [`allocate_zeroed`], [`grow`], [`grow_zeroed`], or [`shrink`] methods,
136///   called on an allocator that's equivalent to this specific allocator; and
137/// * the memory block has not subsequently been [*invalidated*].
138///
139/// ### Invalidating memory blocks
140///
141/// A memory block that is currently allocated becomes *invalidated* when one
142/// of the following happens:
143/// * The memory block is deallocated. This occurs when the memory block
144///   is passed as an argument to a [`deallocate`] call, or when it is passed
145///   as an argument to a [`grow`], [`grow_zeroed`] or [`shrink`] call that returns `Ok`.
146/// * For all (equivalent) allocators that this memory block is currently allocated by, at
147///   least one of the following has occurred:
148///   * The allocator's destructor runs.
149///   * The allocator is mutated through a public or otherwise untrusted API taking `&mut` access.
150///   * One of the borrow-checker lifetimes in the allocator's type expires.
151///
152/// Note that these conditions imply that a collection may ensure that
153/// any specific currently allocated memory block won't be invalidated by:
154/// * not deallocating that memory block,
155/// * owning an allocator that memory block is allocated with, and
156/// * not publicly exposing `&mut` access to that allocator.
157///
158/// Also note that safe public API of an allocator with `&` access is not
159/// allowed to invalidate its memory blocks. Furthermore, unsafe public API
160/// of an allocator with `&` access must document that they invalidate
161/// memory blocks (e.g., by calling `deallocate`) if they do. Therefore,
162/// a collection may safely expose `&` access to its allocator.
163///
164/// Also note that, even in cases where there are other "alive" allocators known
165/// to be equivalent to a given collection's allocator, most collections still should
166/// not publicly expose `&mut` access to their allocators. The fact that there are
167/// other "alive" allocators would prevent this `&mut` access from invalidating
168/// the collection's memory block, but public `&mut` access is still likely to
169/// be unsound, since a user could replace the collection's allocator with
170/// a non-equivalent allocator, causing the collection to deallocate its memory
171/// with the wrong allocator.
172///
173/// [`allocate`]: Allocator::allocate
174/// [`allocate_zeroed`]: Allocator::allocate_zeroed
175/// [`grow`]: Allocator::grow
176/// [`grow_zeroed`]: Allocator::grow_zeroed
177/// [`shrink`]: Allocator::shrink
178/// [`deallocate`]: Allocator::deallocate
179///
180/// ### Memory fitting
181///
182/// Some of the methods require that a `layout` *fits* a memory block or vice versa. This means
183/// that the following conditions must hold:
184///  * the memory block must be *currently allocated* by the allocator,
185///  * [`layout.align()`] must be the same as the alignment of the layout used to allocate the block, and
186///  * [`layout.size()`] must fall in the range `min ..= max`, where:
187///    - `min` is the size of the layout used to allocate the block, and
188///    - `max` is the actual size returned from [`allocate`], [`allocate_zeroed`],
189///      [`grow`], [`grow_zeroed`], or [`shrink`].
190///
191/// [`layout.align()`]: Layout::align
192/// [`layout.size()`]: Layout::size
193///
194/// # Safety
195///
196/// Implementors of `Allocator` must ensure that a memory block that
197/// is [*currently allocated*] by the allocator points to valid memory
198/// until that memory block is [*invalidated*]. The implementor must also
199/// not violate this invariant of `Allocator` via allocator equivalences
200/// that are in the implementor's control.
201///
202/// Additionally, any memory block returned by the allocator must
203/// satisfy the allocation invariants described in `core::ptr`.
204/// In particular, if a block has base address `p` and size `n`,
205/// then `p as usize + n <= usize::MAX` must hold. These blocks must also
206/// be wholly disjoint.
207///
208/// This ensures that pointer arithmetic within the allocation
209/// (for example, `ptr.add(len)`) cannot overflow the address space, and
210/// that it is possible to perform nonoverlapping copies between allocations.
211///
212/// None of the allocating or deallocating methods may unwind. This restriction
213/// may be lifted in the future by ensuring unwinding out of an allocating function always
214/// aborts. If an implementor of `Allocator` also has drop glue or directly implements `Drop`,
215/// dropping the allocator must not result in an unwind.
216///
217/// It is undefined behavior for the allocator to read, write, or deallocate any memory that
218/// is currently allocated. This memory is owned by the user; the allocator must not touch it.
219///
220/// Lastly, the methods on this trait must be *correct*; in particular, the layout requested
221/// must be respected, calls must zero out memory if the documentation so requires,
222/// returning an `AllocError` from a reallocating method must indeed ensure that
223/// the old pointer was not invalidated, and de/reallocating calls must accept layouts
224/// in the ranges defined by their documentation.
225///
226/// [*currently allocated*]: #currently-allocated-memory
227/// [*invalidated*]: #invalidating-memory-blocks
228// NOTE: the above bound on allocating methods not unwinding, alongside the similar
229// bound on `AllocatorClone`, are currently load-bearing in std! see the below issues
230// and make sure they cannot be triggered before relaxing this:
231// https://rust.tf/156490
232// https://rust.tf/159982
233#[stable(feature = "allocator_api", since = "1.100.0")]
234#[rustc_const_unstable(feature = "const_heap", issue = "79597")]
235pub const unsafe trait Allocator {
236    /// Attempts to allocate a block of memory.
237    ///
238    /// On success, returns a [`NonNull<[u8]>`][NonNull] meeting the size and alignment
239    /// guarantees of `layout`. The returned block may have a larger size than specified
240    /// by `layout.size()`, and may or may not have its contents initialized.
241    ///
242    /// It is recommended that overallocating as per the above is only performed if doing so
243    /// is cheap; there is no guarantee that the caller is able to take advantage of the
244    /// returned excess. Implementors are free to e.g. provide an alternate method to query
245    /// available excess if doing so is expensive and should be left to the caller.
246    ///
247    /// The returned block may be uninitialized, so it is unsound to read it
248    /// before it is written. Use [`allocate_zeroed`](Self::allocate_zeroed) if
249    /// zero-initialized memory is needed.
250    ///
251    /// Note that the returned block of memory is considered [*currently allocated*]
252    /// with this allocator (and equivalent allocators).
253    /// Therefore, it is the responsibility of implementors of `Allocator` to make sure that
254    /// this block of memory remains valid until it is [*invalidated*].
255    ///
256    /// [*currently allocated*]: #currently-allocated-memory
257    /// [*invalidated*]: #invalidating-memory-blocks
258    ///
259    /// # Errors
260    ///
261    /// Returning `Err` indicates that either memory is exhausted or `layout` does not meet
262    /// allocator's size or alignment constraints.
263    ///
264    /// Implementations are encouraged to return `Err` on memory exhaustion rather than
265    /// aborting, but this is not a strict requirement. (Specifically: it is *legal* to implement
266    /// this trait atop an underlying native allocation library that aborts on memory exhaustion.)
267    ///
268    /// Clients wishing to abort computation in response to an allocation error are encouraged to
269    /// call the [`handle_alloc_error`] function, rather than directly invoking `panic!` or similar.
270    ///
271    /// [`handle_alloc_error`]: ../../alloc/alloc/fn.handle_alloc_error.html
272    ///
273    /// # Examples
274    ///
275    /// ```
276    /// use std::alloc::{Allocator, Layout, System};
277    ///
278    /// let s = "Hello, world!";
279    /// let layout = Layout::array::<u8>(s.len()).unwrap();
280    // FIXME(slice_ptr_get): use `.as_mut_ptr()` once stable
281    /// let ptr = System.allocate(layout).expect("allocation failed").cast::<u8>();
282    ///
283    /// // SAFETY: the block is at least `s.len()` bytes long and was just allocated,
284    /// // so it cannot overlap `s`.
285    /// unsafe { ptr.as_ptr().copy_from_nonoverlapping(s.as_ptr(), s.len()) };
286    ///
287    /// // SAFETY: the first `s.len()` bytes were initialized by the copy above.
288    /// let bytes = unsafe { std::slice::from_raw_parts(ptr.as_ptr(), s.len()) };
289    /// assert_eq!(bytes, s.as_bytes());
290    ///
291    /// // SAFETY: `ptr` was allocated by `System` with `layout`.
292    /// unsafe { System.deallocate(ptr, layout) };
293    /// ```
294    #[stable(feature = "allocator_api", since = "1.100.0")]
295    fn allocate(&self, layout: Layout) -> Result<NonNull<[u8]>, AllocError>;
296
297    /// Behaves like `allocate`, but also ensures that the returned memory is zero-initialized.
298    ///
299    /// # Errors
300    ///
301    /// Returning `Err` indicates that either memory is exhausted or `layout` does not meet
302    /// allocator's size or alignment constraints.
303    ///
304    /// Implementations are encouraged to return `Err` on memory exhaustion rather than
305    /// aborting, but this is not a strict requirement. (Specifically: it is *legal* to implement
306    /// this trait atop an underlying native allocation library that aborts on memory exhaustion.)
307    ///
308    /// Clients wishing to abort computation in response to an allocation error are encouraged to
309    /// call the [`handle_alloc_error`] function, rather than directly invoking `panic!` or similar.
310    ///
311    /// [`handle_alloc_error`]: ../../alloc/alloc/fn.handle_alloc_error.html
312    ///
313    /// # Examples
314    ///
315    /// ```
316    /// use std::alloc::{Allocator, Layout, System};
317    ///
318    /// let layout = Layout::new::<u64>();
319    /// let ptr = System.allocate_zeroed(layout).expect("allocation failed");
320    ///
321    /// // N.B. the below would be unsound with `allocate` rather than `allocate_zeroed`.
322    /// // SAFETY: `allocate_zeroed` returns a valid, initialized block.
323    /// let bytes = unsafe { ptr.as_ref() };
324    /// assert!(bytes.iter().all(|&b| b == 0));
325    ///
326    /// // SAFETY: `ptr` was allocated by `System` with `layout`.
327    // FIXME(slice_ptr_get): use `.as_mut_ptr()` once stable
328    /// unsafe { System.deallocate(ptr.cast(), layout) };
329    /// ```
330    #[stable(feature = "allocator_api", since = "1.100.0")]
331    fn allocate_zeroed(&self, layout: Layout) -> Result<NonNull<[u8]>, AllocError> {
332        let ptr = self.allocate(layout)?;
333        // SAFETY: `alloc` returns a valid memory block
334        unsafe { ptr.as_non_null_ptr().as_ptr().write_bytes(0, ptr.len()) }
335        Ok(ptr)
336    }
337
338    /// Deallocates the memory referenced by `ptr`.
339    ///
340    /// # Safety
341    ///
342    /// * `ptr` must denote a block of memory [*currently allocated*] via this allocator, and
343    /// * `layout` must [*fit*] that block of memory.
344    ///
345    /// Note that it is *immediate* language UB for a deallocation or reallocation to
346    /// invalidate any outstanding references, smart pointers, etc.; thus, notably, an
347    /// allocator that has been moved into its own [*currently allocated*] memory may
348    /// not have its backing memory be freed, even if the allocator is never used again
349    /// afterwards. This is due to the fact that such a deallocation would invalidate the
350    /// `&self` reference passed to this method.
351    ///
352    /// [*currently allocated*]: #currently-allocated-memory
353    /// [*fit*]: #memory-fitting
354    #[stable(feature = "allocator_api", since = "1.100.0")]
355    unsafe fn deallocate(&self, ptr: NonNull<u8>, layout: Layout);
356
357    /// Attempts to extend the memory block.
358    ///
359    /// Returns a new [`NonNull<[u8]>`][NonNull] containing a pointer and the actual size of the allocated
360    /// memory. The pointer is suitable for holding data described by `new_layout`. To accomplish
361    /// this, the allocator may extend the allocation referenced by `ptr` to fit the new layout.
362    ///
363    /// If this returns `Ok`, then the memory block referenced by `ptr` has been [*invalidated*].
364    /// The old `ptr` must not be used to access the memory, even if the allocation was grown in-place.
365    /// The newly returned pointer is the only valid pointer for accessing this memory now.
366    /// All bytes past `old_layout.size()` should be assumed to be uninitialised, so it is
367    /// unsound to read them before they are written. Use [`grow_zeroed`](Self::grow_zeroed)
368    /// if the new bytes should be zero-initialized.
369    ///
370    /// If this method returns `Err`, then the memory block has not been *invalidated*,
371    /// and the contents of the memory block are unaltered.
372    ///
373    /// # Safety
374    ///
375    /// * `ptr` must denote a block of memory [*currently allocated*] via this allocator.
376    /// * `old_layout` must [*fit*] that block of memory (The `new_layout` argument need not fit it.).
377    /// * `new_layout.size()` must be greater than or equal to `old_layout.size()`.
378    ///
379    /// Note that `new_layout.align()` need not be the same as `old_layout.align()`.
380    ///
381    /// [*currently allocated*]: #currently-allocated-memory
382    /// [*fit*]: #memory-fitting
383    /// [*invalidated*]: #invalidating-memory-blocks
384    ///
385    /// # Errors
386    ///
387    /// Returns `Err` if the new layout does not meet the allocator's size and alignment
388    /// constraints of the allocator, or if growing otherwise fails.
389    ///
390    /// Implementations are encouraged to return `Err` on memory exhaustion rather than
391    /// aborting, but this is not a strict requirement. (Specifically: it is *legal* to implement
392    /// this trait atop an underlying native allocation library that aborts on memory exhaustion.)
393    ///
394    /// Clients wishing to abort computation in response to an allocation error are encouraged to
395    /// call the [`handle_alloc_error`] function, rather than directly invoking `panic!` or similar.
396    ///
397    /// [`handle_alloc_error`]: ../../alloc/alloc/fn.handle_alloc_error.html
398    ///
399    /// # Examples
400    ///
401    /// ```
402    /// use std::alloc::{Allocator, Layout, System};
403    ///
404    /// let s1 = "Hello";
405    /// let s2 = ", world!";
406    ///
407    /// let old_layout = Layout::array::<u8>(s1.len()).unwrap();
408    // FIXME(slice_ptr_get): use `.as_mut_ptr()` once stable
409    /// let ptr = System.allocate(old_layout).expect("allocation failed").cast::<u8>();
410    ///
411    /// // SAFETY: the block is at least `s1.len()` bytes long and was just allocated,
412    /// // so it cannot overlap `s1`.
413    /// unsafe { ptr.as_ptr().copy_from_nonoverlapping(s1.as_ptr(), s1.len()) };
414    ///
415    /// let new_layout = Layout::array::<u8>(s1.len() + s2.len()).unwrap();
416    ///
417    /// // N.B. the original `ptr` is invalidated by this operation
418    /// // SAFETY: `ptr` is currently allocated by `System` with `old_layout`,
419    /// // and `new_layout` is at least as large as `old_layout`.
420    // FIXME(slice_ptr_get): use `.as_mut_ptr()` once stable
421    /// let ptr = unsafe { System.grow(ptr, old_layout, new_layout) }
422    ///     .expect("grow failed").cast::<u8>();
423    ///
424    /// // SAFETY: the block is at least `s1.len() + s2.len()` bytes long, so writing
425    /// // `s2.len()` bytes at offset `s1.len()` stays in bounds; it cannot overlap `s2`.
426    /// unsafe {
427    ///     ptr.as_ptr().add(s1.len()).copy_from_nonoverlapping(s2.as_ptr(), s2.len());
428    /// }
429    ///
430    /// // SAFETY: all bytes within `new_layout.size()` are now initialized.
431    /// let bytes = unsafe { std::slice::from_raw_parts(ptr.as_ptr(), new_layout.size()) };
432    /// assert_eq!(bytes, b"Hello, world!");
433    ///
434    /// // SAFETY: `ptr` is currently allocated by `System` with `new_layout`.
435    /// unsafe { System.deallocate(ptr, new_layout) };
436    /// ```
437    #[stable(feature = "allocator_api", since = "1.100.0")]
438    unsafe fn grow(
439        &self,
440        ptr: NonNull<u8>,
441        old_layout: Layout,
442        new_layout: Layout,
443    ) -> Result<NonNull<[u8]>, AllocError> {
444        debug_assert!(
445            new_layout.size() >= old_layout.size(),
446            "`new_layout.size()` must be greater than or equal to `old_layout.size()`"
447        );
448
449        let new_ptr = self.allocate(new_layout)?;
450
451        // SAFETY: because `new_layout.size()` must be greater than or equal to
452        // `old_layout.size()`, both the old and new memory allocation are valid for reads and
453        // writes for `old_layout.size()` bytes. Also, because the old allocation wasn't yet
454        // deallocated, it cannot overlap `new_ptr`. Thus, the call to `copy_nonoverlapping` is
455        // safe. The safety contract for `dealloc` must be upheld by the caller.
456        unsafe {
457            ptr::copy_nonoverlapping(ptr.as_ptr(), new_ptr.as_mut_ptr(), old_layout.size());
458            self.deallocate(ptr, old_layout);
459        }
460
461        Ok(new_ptr)
462    }
463
464    /// Behaves like `grow`, but also ensures that the new contents are set to zero before being
465    /// returned.
466    ///
467    /// The memory block will contain the following contents after a successful call to
468    /// `grow_zeroed`:
469    ///   * Bytes `0..old_layout.size()` are preserved from the original allocation.
470    ///   * Bytes `old_layout.size()..new_size` are zeroed. `new_size` refers to the size
471    ///     of the memory block returned by the `grow_zeroed` call, which may be larger than
472    ///     `new_layout.size()`.
473    ///
474    /// # Safety
475    ///
476    /// * `ptr` must denote a block of memory [*currently allocated*] via this allocator.
477    /// * `old_layout` must [*fit*] that block of memory (The `new_layout` argument need not fit it.).
478    /// * `new_layout.size()` must be greater than or equal to `old_layout.size()`.
479    ///
480    /// Note that `new_layout.align()` need not be the same as `old_layout.align()`.
481    ///
482    /// [*currently allocated*]: #currently-allocated-memory
483    /// [*fit*]: #memory-fitting
484    ///
485    /// # Errors
486    ///
487    /// Returns `Err` if the new layout does not meet the allocator's size and alignment
488    /// constraints of the allocator, or if growing otherwise fails.
489    ///
490    /// Implementations are encouraged to return `Err` on memory exhaustion rather than
491    /// aborting, but this is not a strict requirement. (Specifically: it is *legal* to implement
492    /// this trait atop an underlying native allocation library that aborts on memory exhaustion.)
493    ///
494    /// Clients wishing to abort computation in response to an allocation error are encouraged to
495    /// call the [`handle_alloc_error`] function, rather than directly invoking `panic!` or similar.
496    ///
497    /// [`handle_alloc_error`]: ../../alloc/alloc/fn.handle_alloc_error.html
498    #[stable(feature = "allocator_api", since = "1.100.0")]
499    unsafe fn grow_zeroed(
500        &self,
501        ptr: NonNull<u8>,
502        old_layout: Layout,
503        new_layout: Layout,
504    ) -> Result<NonNull<[u8]>, AllocError> {
505        debug_assert!(
506            new_layout.size() >= old_layout.size(),
507            "`new_layout.size()` must be greater than or equal to `old_layout.size()`"
508        );
509
510        let new_ptr = self.allocate_zeroed(new_layout)?;
511
512        // SAFETY: because `new_layout.size()` must be greater than or equal to
513        // `old_layout.size()`, both the old and new memory allocation are valid for reads and
514        // writes for `old_layout.size()` bytes. Also, because the old allocation wasn't yet
515        // deallocated, it cannot overlap `new_ptr`. Thus, the call to `copy_nonoverlapping` is
516        // safe. The safety contract for `dealloc` must be upheld by the caller.
517        unsafe {
518            ptr::copy_nonoverlapping(ptr.as_ptr(), new_ptr.as_mut_ptr(), old_layout.size());
519            self.deallocate(ptr, old_layout);
520        }
521
522        Ok(new_ptr)
523    }
524
525    /// Attempts to shrink the memory block.
526    ///
527    /// Returns a new [`NonNull<[u8]>`][NonNull] containing a pointer and the actual size of the allocated
528    /// memory. The pointer is suitable for holding data described by `new_layout`. To accomplish
529    /// this, the allocator may shrink the allocation referenced by `ptr` to fit the new layout.
530    ///
531    ///
532    /// If this returns `Ok`, then the memory block referenced by `ptr` has been [*invalidated*].
533    /// The old `ptr` must not be used to access the memory, even if the allocation was shrunk in-place.
534    /// The newly returned pointer is the only valid pointer for accessing this memory now.
535    /// All bytes past `new_layout.size()` should be assumed to be uninitialised.
536    ///
537    /// If this method returns `Err`, then the memory block has not been *invalidated*,
538    /// and the contents of the memory block are unaltered.
539    ///
540    /// # Safety
541    ///
542    /// * `ptr` must denote a block of memory [*currently allocated*] via this allocator.
543    /// * `old_layout` must [*fit*] that block of memory (The `new_layout` argument need not fit it.).
544    /// * `new_layout.size()` must be smaller than or equal to `old_layout.size()`.
545    ///
546    /// Note that `new_layout.align()` need not be the same as `old_layout.align()`.
547    ///
548    /// [*currently allocated*]: #currently-allocated-memory
549    /// [*fit*]: #memory-fitting
550    /// [*invalidated*]: #invalidating-memory-blocks
551    ///
552    /// # Errors
553    ///
554    /// Returns `Err` if the new layout does not meet the allocator's size and alignment
555    /// constraints of the allocator, or if shrinking otherwise fails.
556    ///
557    /// Implementations are encouraged to return `Err` on memory exhaustion rather than
558    /// aborting, but this is not a strict requirement. (Specifically: it is *legal* to implement
559    /// this trait atop an underlying native allocation library that aborts on memory exhaustion.)
560    ///
561    /// Clients wishing to abort computation in response to an allocation error are encouraged to
562    /// call the [`handle_alloc_error`] function, rather than directly invoking `panic!` or similar.
563    ///
564    /// [`handle_alloc_error`]: ../../alloc/alloc/fn.handle_alloc_error.html
565    ///
566    /// # Examples
567    ///
568    /// ```
569    /// use std::alloc::{Allocator, Layout, System};
570    ///
571    /// let old_layout = Layout::array::<u32>(4).unwrap();
572    /// let ptr = System.allocate(old_layout).expect("allocation failed");
573    ///
574    /// // SAFETY: the block holds at least 4 `u32`s and is aligned for `u32`.
575    /// unsafe { ptr.cast::<[u32; 4]>().write([7, 8, 9, 10]) };
576    ///
577    /// let new_layout = Layout::array::<u32>(2).unwrap();
578    ///
579    /// // N.B. the original `ptr` is invalidated by this operation
580    /// // SAFETY: `ptr` is currently allocated by `System` with `old_layout`,
581    /// // and `new_layout` is no larger than `old_layout`.
582    /// let ptr = unsafe { System.shrink(ptr.cast(), old_layout, new_layout) }
583    ///     .expect("shrink failed");
584    ///
585    /// // The contents that fit in the new layout are preserved.
586    /// // SAFETY: the first two `u32`s were written above and `shrink` kept them.
587    /// assert_eq!(unsafe { ptr.cast::<[u32; 2]>().read() }, [7, 8]);
588    ///
589    /// // SAFETY: `ptr` is currently allocated by `System` with `new_layout`.
590    /// unsafe { System.deallocate(ptr.cast(), new_layout) };
591    /// ```
592    #[stable(feature = "allocator_api", since = "1.100.0")]
593    unsafe fn shrink(
594        &self,
595        ptr: NonNull<u8>,
596        old_layout: Layout,
597        new_layout: Layout,
598    ) -> Result<NonNull<[u8]>, AllocError> {
599        debug_assert!(
600            new_layout.size() <= old_layout.size(),
601            "`new_layout.size()` must be smaller than or equal to `old_layout.size()`"
602        );
603
604        let new_ptr = self.allocate(new_layout)?;
605
606        // SAFETY: because `new_layout.size()` must be lower than or equal to
607        // `old_layout.size()`, both the old and new memory allocation are valid for reads and
608        // writes for `new_layout.size()` bytes. Also, because the old allocation wasn't yet
609        // deallocated, it cannot overlap `new_ptr`. Thus, the call to `copy_nonoverlapping` is
610        // safe. The safety contract for `dealloc` must be upheld by the caller.
611        unsafe {
612            ptr::copy_nonoverlapping(ptr.as_ptr(), new_ptr.as_mut_ptr(), new_layout.size());
613            self.deallocate(ptr, old_layout);
614        }
615
616        Ok(new_ptr)
617    }
618}
619
620/// An [`Allocator`] that can be registered as the standard library’s default
621/// through the `#[global_allocator]` attribute.
622///
623/// Types implementing this trait can be used as the default allocator for
624/// memory allocations through `Box`, `Vec` and the collection types. For
625/// instance, the `System` allocator implements this trait, and thus can be
626/// explicitly set as the default like so:
627/// ```
628/// use std::alloc::System;
629///
630/// #[global_allocator]
631/// static ALLOCATOR: System = System;
632/// ```
633///
634/// The `Global` allocator forwards all memory allocation requests to the
635/// `static` annotated with `#[global_allocator]`. Hence, `Global` does not
636/// implement `GlobalAllocator` itself, as that would lead to infinite recursion.
637///
638/// # Note to implementors
639///
640/// This trait is used to prevent the infinite recursion that would occur if the
641/// default allocator were to attempt to allocate memory through `Global` (and
642/// thus from itself).
643///
644/// When to implement this trait:
645/// * for custom global allocators that only use system memory allocation
646///   services.
647/// * for allocators that wrap another allocator that implements `GlobalAllocator`.
648///
649/// When **not** to implement this trait:
650/// * for wrappers of arbitrary allocators (which might end up being `Global`,
651///   leading to infinite recursion).
652///
653/// # Safety
654///
655/// When implementing a global allocator, one has to be careful not to create an infinitely
656/// recursive implementation by accident, as many constructs in the Rust standard library may
657/// allocate in their implementation. For example, on some platforms, [`std::sync::Mutex`] may
658/// allocate, so using it is highly problematic in a global allocator.
659///
660/// For this reason, one should generally stick to library features available through
661/// [`core`], and avoid using [`std`] in a global allocator. A few features from [`std`] are
662/// guaranteed to not use `#[global_allocator]` to allocate:
663///
664///  - [`std::thread_local`],
665///  - [`std::thread::current`],
666///  - [`std::thread::park`] and [`std::thread::Thread`]'s [`unpark`] method and
667/// [`Clone`] implementation.
668///
669/// [`std`]: ../../std/index.html
670/// [`std::sync::Mutex`]: ../../std/sync/struct.Mutex.html
671/// [`std::thread_local`]: ../../std/macro.thread_local.html
672/// [`std::thread::current`]: ../../std/thread/fn.current.html
673/// [`std::thread::park`]: ../../std/thread/fn.park.html
674/// [`std::thread::Thread`]: ../../std/thread/struct.Thread.html
675/// [`unpark`]: ../../std/thread/struct.Thread.html#method.unpark
676#[unstable(feature = "allocator_ext", issue = "163177", implied_by = "allocator_api")]
677#[expect(multiple_supertrait_upcastable)]
678pub unsafe trait GlobalAllocator: StaticAllocator + Sync + 'static {}
679
680/// Marks a type's [`Clone`] implementation as sound with regard to [`Allocator`] equivalence.
681/// Implementors must ensure that, upon cloning, the two allocators are equivalent
682/// (i.e. it is possible to free memory with one that was allocated with the other).
683/// Further, mutable accesses such as moving or dropping the allocator must not invalidate
684/// its currently allocated blocks at least so long as clones exist.
685///
686/// Additionally, the bound that allocators do not unwind when (de)allocating also applies
687/// to guaranteeing allocators will not unwind when cloned.
688///
689/// It must also be the case that types which are `AllocatorClone` are either explicitly not
690/// copyable (such as by containing a `!Copy` field) or that copying them also respects allocator
691/// equivalence as if it had been a clone.
692#[unstable(feature = "allocator_ext", issue = "163177", implied_by = "allocator_api")]
693pub unsafe trait AllocatorClone: Allocator + Clone {}
694
695/// Marks that an allocator and its supertypes will never invalidate currently allocated
696/// memory unless explicitly deallocated via a call to a deallocating method, even if
697/// dropped or if the allocator's lifetime expires.
698///
699/// This is a necessity in conjunction with [`Pin`], as only allocators that promise
700/// memory is never reused without a destructor running may be used to back a pinned pointer.
701///
702/// # Safety
703///
704/// Implementors must ensure that memory blocks are *only, ever* invalidated by a
705/// call to a de/reallocating method on `Allocator`, and that this holds true for all
706/// possible instances of all subtypes of the implementor as well.
707///
708/// These requirements trivially apply to allocators that always maintain global state, such as
709/// `System` or `Global`. However, due to subtype coercion, it is *not* sound to implement
710/// for an arbitrary `Allocator + 'static` due to [edge-case interactions][unsound] with e.g.
711/// `Pin::clone`. Namely, an impl of `StaticAllocator for MyAllocator + 'long` guarantees that any
712/// value of `MyAllocator + 'short` also fulfills the requirements of `StaticAllocator`.
713///
714/// The following must thus be guaranteed:
715/// - the `Drop` impl of the allocator does not invalidate any allocations;
716/// - the allocator does not expose a safe API surface that allows invalidating
717///   its allocations;
718/// - the allocator's lifetime expiring does not invalidate any allocations;
719/// - the above also hold for all equivalent allocators (see [`Allocator`] docs).
720///
721/// [`Pin`]: ../../core/pin/struct.Pin.html
722/// [unsound]: https://github.com/rust-lang/rust/issues/157089
723#[unstable(feature = "allocator_ext", issue = "163177", implied_by = "allocator_api")]
724pub unsafe trait StaticAllocator: Allocator {}
725
726#[stable(feature = "allocator_api", since = "1.100.0")]
727#[rustc_const_unstable(feature = "const_heap", issue = "79597")]
728const unsafe impl<A> Allocator for &A
729where
730    A: [const] Allocator + ?Sized,
731{
732    #[inline]
733    fn allocate(&self, layout: Layout) -> Result<NonNull<[u8]>, AllocError> {
734        (**self).allocate(layout)
735    }
736
737    #[inline]
738    fn allocate_zeroed(&self, layout: Layout) -> Result<NonNull<[u8]>, AllocError> {
739        (**self).allocate_zeroed(layout)
740    }
741
742    #[inline]
743    unsafe fn deallocate(&self, ptr: NonNull<u8>, layout: Layout) {
744        // SAFETY: the safety contract must be upheld by the caller
745        unsafe { (**self).deallocate(ptr, layout) }
746    }
747
748    #[inline]
749    unsafe fn grow(
750        &self,
751        ptr: NonNull<u8>,
752        old_layout: Layout,
753        new_layout: Layout,
754    ) -> Result<NonNull<[u8]>, AllocError> {
755        // SAFETY: the safety contract must be upheld by the caller
756        unsafe { (**self).grow(ptr, old_layout, new_layout) }
757    }
758
759    #[inline]
760    unsafe fn grow_zeroed(
761        &self,
762        ptr: NonNull<u8>,
763        old_layout: Layout,
764        new_layout: Layout,
765    ) -> Result<NonNull<[u8]>, AllocError> {
766        // SAFETY: the safety contract must be upheld by the caller
767        unsafe { (**self).grow_zeroed(ptr, old_layout, new_layout) }
768    }
769
770    #[inline]
771    unsafe fn shrink(
772        &self,
773        ptr: NonNull<u8>,
774        old_layout: Layout,
775        new_layout: Layout,
776    ) -> Result<NonNull<[u8]>, AllocError> {
777        // SAFETY: the safety contract must be upheld by the caller
778        unsafe { (**self).shrink(ptr, old_layout, new_layout) }
779    }
780}
781
782#[stable(feature = "allocator_api", since = "1.100.0")]
783#[rustc_const_unstable(feature = "const_heap", issue = "79597")]
784const unsafe impl<A> Allocator for &mut A
785where
786    A: [const] Allocator + ?Sized,
787{
788    #[inline]
789    fn allocate(&self, layout: Layout) -> Result<NonNull<[u8]>, AllocError> {
790        (**self).allocate(layout)
791    }
792
793    #[inline]
794    fn allocate_zeroed(&self, layout: Layout) -> Result<NonNull<[u8]>, AllocError> {
795        (**self).allocate_zeroed(layout)
796    }
797
798    #[inline]
799    unsafe fn deallocate(&self, ptr: NonNull<u8>, layout: Layout) {
800        // SAFETY: the safety contract must be upheld by the caller
801        unsafe { (**self).deallocate(ptr, layout) }
802    }
803
804    #[inline]
805    unsafe fn grow(
806        &self,
807        ptr: NonNull<u8>,
808        old_layout: Layout,
809        new_layout: Layout,
810    ) -> Result<NonNull<[u8]>, AllocError> {
811        // SAFETY: the safety contract must be upheld by the caller
812        unsafe { (**self).grow(ptr, old_layout, new_layout) }
813    }
814
815    #[inline]
816    unsafe fn grow_zeroed(
817        &self,
818        ptr: NonNull<u8>,
819        old_layout: Layout,
820        new_layout: Layout,
821    ) -> Result<NonNull<[u8]>, AllocError> {
822        // SAFETY: the safety contract must be upheld by the caller
823        unsafe { (**self).grow_zeroed(ptr, old_layout, new_layout) }
824    }
825
826    #[inline]
827    unsafe fn shrink(
828        &self,
829        ptr: NonNull<u8>,
830        old_layout: Layout,
831        new_layout: Layout,
832    ) -> Result<NonNull<[u8]>, AllocError> {
833        // SAFETY: the safety contract must be upheld by the caller
834        unsafe { (**self).shrink(ptr, old_layout, new_layout) }
835    }
836}
837
838/// Defers to the pinned allocator. Requires that the smart pointer inside the
839/// [`Pin`](core::pin::Pin) is well-behaved.
840///
841/// This trait impl is unstable and only usable on nightly with `feature(allocator_ext)`.
842/// It may be changed or removed in the future.
843// FIXME: We may want to weaken the `Allocator` bound here to some `PinnedAllocator`
844// supertrait that takes `self: Pin<&Self>` in its methods. This should be non-breaking
845// to do later once we have a way to add supertraits to traits after the fact
846// (e.g. the `auto impl` proposal)
847#[unstable(feature = "allocator_ext", issue = "163177", implied_by = "allocator_api")]
848#[rustc_const_unstable(feature = "const_heap", issue = "79597")]
849#[unstable_feature_bound(allocator_ext)]
850const unsafe impl<P> Allocator for core::pin::Pin<P>
851where
852    P: [const] core::ops::Deref<Target: [const] Allocator> + core::pin::PinSafePointer,
853{
854    #[inline]
855    fn allocate(&self, layout: Layout) -> Result<NonNull<[u8]>, AllocError> {
856        (**self).allocate(layout)
857    }
858
859    #[inline]
860    fn allocate_zeroed(&self, layout: Layout) -> Result<NonNull<[u8]>, AllocError> {
861        (**self).allocate_zeroed(layout)
862    }
863
864    #[inline]
865    unsafe fn deallocate(&self, ptr: NonNull<u8>, layout: Layout) {
866        // SAFETY: the safety contract must be upheld by the caller
867        unsafe { (**self).deallocate(ptr, layout) }
868    }
869
870    #[inline]
871    unsafe fn grow(
872        &self,
873        ptr: NonNull<u8>,
874        old_layout: Layout,
875        new_layout: Layout,
876    ) -> Result<NonNull<[u8]>, AllocError> {
877        // SAFETY: the safety contract must be upheld by the caller
878        unsafe { (**self).grow(ptr, old_layout, new_layout) }
879    }
880
881    #[inline]
882    unsafe fn grow_zeroed(
883        &self,
884        ptr: NonNull<u8>,
885        old_layout: Layout,
886        new_layout: Layout,
887    ) -> Result<NonNull<[u8]>, AllocError> {
888        // SAFETY: the safety contract must be upheld by the caller
889        unsafe { (**self).grow_zeroed(ptr, old_layout, new_layout) }
890    }
891
892    #[inline]
893    unsafe fn shrink(
894        &self,
895        ptr: NonNull<u8>,
896        old_layout: Layout,
897        new_layout: Layout,
898    ) -> Result<NonNull<[u8]>, AllocError> {
899        // SAFETY: the safety contract must be upheld by the caller
900        unsafe { (**self).shrink(ptr, old_layout, new_layout) }
901    }
902}
903
904/// This trait impl is unstable and only usable on nightly with `feature(allocator_ext)`.
905#[unstable(feature = "allocator_ext", issue = "163177", implied_by = "allocator_api")]
906#[unstable_feature_bound(allocator_ext)]
907impl<P> AllocatorNightly for core::pin::Pin<P> where
908    P: core::ops::Deref<Target: Allocator> + core::pin::PinSafePointer
909{
910}
911
912#[unstable(feature = "allocator_ext", issue = "163177", implied_by = "allocator_api")]
913unsafe impl<A: Allocator + ?Sized> AllocatorClone for &A {}
914
915// If an allocator is `StaticAllocator` all equivalent allocators must also uphold
916// its semantics, and references are equivalent to the allocator they reference.
917#[unstable(feature = "allocator_ext", issue = "163177", implied_by = "allocator_api")]
918unsafe impl<A: StaticAllocator + ?Sized> StaticAllocator for &A {}
919
920#[unstable(feature = "allocator_ext", issue = "163177", implied_by = "allocator_api")]
921unsafe impl<A: StaticAllocator + ?Sized> StaticAllocator for &mut A {}
922
923// FIXME: The safety requirements for `PinSafePointer` are not strict enough to
924// ensure correctness of this impl, due to the "all instances of all supertypes"
925// requirement of `StaticAllocator` (though no implementors of `PinSafePointer`
926// currently violate this).
927// The impl is mainly a reservation, because `Pin` is `#[fundamental]`.
928#[unstable(feature = "internal_reserve_pin_static_allocator", issue = "none")]
929#[unstable_feature_bound(internal_reserve_pin_static_allocator, allocator_ext)]
930#[doc(hidden)]
931unsafe impl<P> StaticAllocator for core::pin::Pin<P> where
932    P: core::ops::Deref<Target: StaticAllocator> + core::pin::PinSafePointer
933{
934}
935
936/// Allocator marker trait that is only implemented stably for `Global`.
937///
938/// Enabling `feature(allocator_ext)` causes this trait to be implemented for all
939/// allocators in std, and for any downstream allocator that explicitly implements it.
940///
941/// This trait is used as a bound whenever a function constructing
942/// a type with an `#[unstable] A: Allocator = Global` parameter
943/// may be callable for `A != Global`.
944///
945/// This is to prevent stable code from e.g. constructing `Arc<T, NotGlobal>`
946/// using the `From<Box<T, A>> for Arc<T, A>` impl.
947///
948/// Note that this trait *will* be removed in the future, but downstream
949/// allocators should still feel free to implement it on nightly, to
950/// allow their allocator to be used with all unstable allocator APIs.
951#[unstable(feature = "allocator_ext", issue = "163177", implied_by = "allocator_api")]
952pub trait AllocatorNightly: Allocator {}
953
954/// This trait impl is unstable and only usable on nightly with `feature(allocator_ext)`.
955#[unstable(feature = "allocator_ext", issue = "163177", implied_by = "allocator_api")]
956#[unstable_feature_bound(allocator_ext)]
957impl<A: Allocator + ?Sized> AllocatorNightly for &A {}
958
959/// This trait impl is unstable and only usable on nightly with `feature(allocator_ext)`.
960#[unstable(feature = "allocator_ext", issue = "163177", implied_by = "allocator_api")]
961#[unstable_feature_bound(allocator_ext)]
962impl<A: Allocator + ?Sized> AllocatorNightly for &mut A {}