# Allocator stabilisation report
This is the stabilisation report for a subset of the feature `allocator_api`, with tracking issue [#32838](https://github.com/rust-lang/rust/issues/32838) under the purview of wg-allocators, initially proposeed by [RFC #1398](https://rust-lang.github.io/rfcs/1398-kinds-of-allocators.html). The remainder of the feature will be renamed to `allocator_ext`.
This was a collaborative effort of the libs & libs-api teams, wg-allocators, members of types, lang, and opsem, alongside interested parties in the ecosystem and contributors to the initial attempt at stabilisation on GitHub.
## Summary
The following is a proposal following several conversations, [in-person](https://github.com/rust-lang/all-hands-2026/issues/48) and [online](https://rust-lang.zulipchat.com/#narrow/channel/197181-t-libs.2Fwg-allocators), with libs team members and interested ecosystem participants and represents an attempt at stabilising an MVP for the `Allocator` trait and its implementation safety requirements, alongside minimal functionality to make its use possible in the standard library.
While an effort was made to align with the stated positions of the team, the opinions and rationale stated are **the author's own**, and should **not** be seen as representative of the libs(-api) team as a whole except insofar as individual members therein choose to endorse the contents of report. Any mention of "we", "us", etc. should be understood to refer to the author alongside those who have explicitly expressed agreement.
## API & considerations
The stabilised API surface consists of:
```rust
#[rustc_dyn_incompatible_trait]
unsafe trait Allocator {
// Required methods
fn allocate(&self, layout: Layout) -> Result<NonNull<[u8]>, AllocError>;
unsafe fn deallocate(&self, ptr: NonNull<u8>, layout: Layout);
// Provided methods
fn allocate_zeroed(
&self,
layout: Layout,
) -> Result<NonNull<[u8]>, AllocError> { ... }
unsafe fn grow(
&self,
ptr: NonNull<u8>,
old_layout: Layout,
new_layout: Layout,
) -> Result<NonNull<[u8]>, AllocError> { ... }
unsafe fn grow_zeroed(
&self,
ptr: NonNull<u8>,
old_layout: Layout,
new_layout: Layout,
) -> Result<NonNull<[u8]>, AllocError> { ... }
unsafe fn shrink(
&self,
ptr: NonNull<u8>,
old_layout: Layout,
new_layout: Layout,
) -> Result<NonNull<[u8]>, AllocError> { ... }
}
impl<T, A: Allocator> Box<T, A> {
fn new_in(x: T, alloc: A) -> Box<T, A>;
}
impl<T, A: Allocator> Vec<T, A> {
fn new_in(alloc: A) -> Vec<T, A>;
}
struct Vec<T, #[stable(...)] A: Allocator> { ... }
// N.B.: `GlobalAllocator` is an unstable marker subtrait of
// `Allocator + Sync`, currently implemented for `System`.
unsafe impl<A: GlobalAllocator + ?Sized> GlobalAlloc for A {}
unsafe impl<A: Allocator + ?Sized> Allocator for &A { ... }
unsafe impl<A: Allocator + ?Sized> Allocator for Box<A, _> { ... }
unsafe impl<A: Allocator + ?Sized> Allocator for Rc<A, _> { ... }
unsafe impl<A: Allocator + ?Sized> Allocator for Arc<A, _> { ... }
```
The `by_ref` method on `Allocator` was removed, as it was only a postfix syntax convenience (equivalent to writing `(&alloc)`).
The safety requirements on implementors of `Allocator` were tightened to the most restrictive sound form we expect to possibly want, in order to enable us to iterate on the design in the future and relax these bounds if it is deemed possible. Notable changes from the unstable nightly safety documentation include:
- we now require implementors to respect the semantics necessary for code generation to emit `noalias` for the pointers passed into de/reallocating methods;
- the implicit requirement, that the standard library's `Clone for Arc<T, A>` implementation relied on but was improperly documented, for implementors not to invalidate allocated memory on drop or mutable access was made explicit;
- implementors must not unwind from any of the methods on the trait;
- the safety invariants implementors of `Allocator + Clone` must uphold were moved to their own unstable marker subtrait.
## Soundness developments
The process of attempting stabilisation resulted in several soundness issues arising, especially with regard to the interaction between custom allocators and `Box`es. Thus, some points had to be adjusted:
- there existed a requirement for trait implementors to obey certain semantics if an implementor of `Allocator` is also `Clone`, which constituted possible UB if broken. These have been dropped, as unsafe implementors [cannot guard against possible unsoundness](https://github.com/rust-lang/rust/issues/156920) from incorrect implementations in downstream safe code, but the equivalent functionality may be added backwards-compatibly with an unsafe marker trait;
- `Box::into_pin` will not yet be possible with custom allocators. This is because of a [soundness bug](https://github.com/rust-lang/rust/issues/157089) relating to an interaction between the possibility of manually implementing `Clone for Box<T, A>` and `Box` being covariant over `A`, allowing for a pinned box to be cloned with a non-`'static` allocator from one with a correct `'static` allocator subtyped to a non-static one. Making `Box` invariant over the allocator was considered, but it would technically be a [breaking change](https://github.com/rust-lang/rust/issues/153607) to reverse this later. Thus, for now, an unstable and unsafe marker trait will be introduced to mark an allocator as well-behaved even with non-`'static` lifetime (i.e. an allocator that only considers global state and thus is *always* `'static`). This will be implemented for the `Global` and `System` allocators;
- should a way emerge to state `impl !Clone for Pin<Box<T, A>> where A: !'static` (currently, negative lifetime bounds are not supported in the trait solver), this could be relaxed in the future.
## Backwards-compatible changes
Several designs were considered to extend or modify the trait's semantics. We have opted to defer full consideration of many of these for later, as we have determined they can be added backwards-compatibly to the existing API. A list of these is present below, alongside rationale for their postponement.
### `Store` API
This is an alternative, more complex proposal for custom allocators (see the [draft RFC](https://github.com/rust-lang/rfcs/pull/3446)). Per a conversation in-person with one of the authors of the `Store` proposal, we have established that it could be added backwards-compatibly (in `Store` terminology, the stabilised `Allocator` trait is a `PinningMultiStore` with pointer handles). The details were thus deferred for potential post-stabilisation changes.
### Split `Deallocator` trait
[Supertrait item shadowing](https://github.com/rust-lang/rust/issues/89151) alongside a blanket `impl<A: Allocator + ?Sized> Deallocator for A` will allow us to add a `Deallocator` supertrait backwards-compatibly, and to relax the requirements for collection types to insted hold a `Deallocator`. Conversations with those involved in the above issue suggest it is likely for a PR implementing this to be merged in the near future.
### `dyn`-compatibility
The stabilised trait is intentionally marked `dyn`-incompatible for now, but could be made `dyn`-compatible later if we choose to not extend the trait in any `dyn`-compatibility-breaking way. Alternatively, a design was proposed for `dyn`-compatible allocators to implement a different trait `DynAllocator` with the standard library containing an `impl Allocator for dyn DynAllocator`. Regardless, this decision can comfortably be deferred.
### Associated constants or types
Several usecases would be facilitated by having certain associated items on the `Allocator` trait; notably, `const MIN_ALIGN: usize` for the minimum alignment an allocator is always guaranteed to return and a `type Err` as a custom associated type. Adding these backwards-compatibly would rely on default associated constants/types being added to the language, but per a conversation with members of the types team we believe these to be possible in the future.
### `fn reallocate()`
The current design uses dedicated `grow`, `grow_zeroed`, and `shrink` methods instead of a way to reallocate between arbitrary sizes. However, such a function could be added with a defaulted body in the future, forwarding to the extant `grow`/`shrink` implementations.
### Conditional reentrancy in `std`
Not all allocators will be [reentrant in `std`](https://github.com/rust-lang/libs-team/issues/743), and thus the standard library may want to be able to conditionally call the global allocator in areas it has otherwise promised not to. Thus, the proposed unstable `GlobalAllocator: Allocator` marker trait could be extended with a defaulted associated constant `REENTRANT_IN_STD: bool = true` wherein implementors could promise that a certain allocator never calls *any* part of `std`.
## Possible but less clean additions
Several options appeared to signal compelling usecases, but were sufficiently niche that we did not consider them to be blocking for an MVP stabilisation so long as it was realistically possible to express their semantics.
### `grow_in_place()`
There is currently no obvious way to signal through the API whether a move of the data is acceptable when reallocating memory. Though messy, a way to express these semantics with the current design does exist, even if non-obvious:
```rust
struct A;
// `grow`/`grow_zeroed` have non-in-place semantics
unsafe impl Allocator for A { /* ... */ }
struct B(A);
// in-place-grow semantics
unsafe impl Allocator for B { /* ... */ }
impl A {
fn as_pinning(self) -> B { B(self) }
}
impl B {
fn as_nonpinning(self) -> A { self.0 }
}
```
We have decided that this is acceptable, given that it is "only" a point of design and not underlying functionality. A cleaner way to signal such semantics would be of interest for future extensions to the trait.
### Allocation flags
A similar mechanism as for the above can be used to reference a local inside of the allocator, though this could be UB-prone. Alternatively, and much more nicely, optional arguments could allow us to backwards-compatibly extend the trait (assuming implementors as well as callers may ignore optional fields). However, this would depend on the details of such a proposal.
The main stakeholder who approached us with concerns on this topic - Rust for Linux - signalled willingness to maintain a downstream extension trait for such functionality for the time being.
### `NonNull<u8>` return type
Lacking a better way to signal returned vs. requested capacity, and not wishing to duplicate all of the allocating methods, we have decided that we would prefer to keep the wide-pointer return value and potentially use that logic to determine capacity in returned allocations. We believe this to be unlikely to lead to significant performance issues in most cases, since the situation where the capacity is always the same as requested is likely to be optimised away unless a `dyn Allocator` is involved; in that latter case, the performance overhead from a wider pointer is minimal.
Ultimately, it would be possible - if perhaps quite ugly - to add defaulted methods such as `allocate_exactly(layout: Layout) -> Result<NonNull<u8>, AllocError>`. This would likely be reliant on there being meaningful real-world performance indications that this is justified. An example [was brought up](https://godbolt.org/z/Mz7PreGh4) wherein an opaque `dyn Allocator` being used together with slice-returning allocating methods resulted in worse code generation, but this issue appears to be limited to dynamic dispatch.
## Rejected alternative proposals
The following changes were explicitly not made to the API pre-stabilisation, despite it being unlikely that their semantics could be nicely expressed in the (near) future. In all cases, notable arguments existed to make the requested change, but we decided they were not sufficiently compelling. Should a way to express these semantics emerge in the future backwards-compatibly, we would be open to re-reviewing them.
### `NonZeroLayout` arguments
An idea had been proposed to change the signature of the allocating/freeing methods to take a `Layout` that is guaranteed to have a nonzero size.
We determined that API cleanliness and potential simplification of library code (once `const Trait`s are stable, collection types could drop special-case logic when using a `const Allocator` at zero capacity) outweigh the arguments for not allowing zero-sized allocations. As we see it, in the cases where it would genuinely be problematic, this will only move the branch on zero-sized allocation to the other side of the call. At worst, it would put marginally more pressure on a branch predictor.
Though the possibility of zero-size allocations being probematic is often mentioned, we have not seen sufficiently convincing concrete cases where this is the case. One pointed-to example was that of highly performance-sensitive allocators (e.g. bump allocators); however, it appears most of these cases can trivially support zero-size allocations (e.g. bumping by zero). Consequently, we have decided to keep the nicer logic for downstream users of the trait. An argument had also been made around `jemalloc` being unable to correctly handle zero-sized allocations, but this appears to only apply to internal APIs.
A similar idea wherein `allocate` was an unsafe method and support for zero-sized allocations was implementation-defined was rejected on similar usability grounds. Several members of the libs team expressed their opinion that the design of `GlobalAlloc` (featuring a similar unsafe allocating method wherein the caller must guarantee the size is nonzero) was not desirable in hindsight.
## Future work
A large part of the standard library will need review as we determine what the correct way is for various collection and pointer types to work with custom allocators.
Notable points are the `A: Allocator` field on `Box` (note that the same does not apply to `Vec`), which is a fundamental type and thus will require us to adjust the semantics of `#[fundamental]` to express that `Box` is not fundamental over the allocator, and the potential addition of unsafe marker traits to signal certain points regarding the behaviour of an `Allocator` (e.g. the previously-discarded note regarding soundness after `Clone`).
## Outlined potential extensions
The following is a possible future outline of what the `Allocator` trait and related might look like under this proposal, assuming both of supertrait item shadowing and defaulted associated items being added:
```rust
unsafe trait Allocator: Deallocator {
const MIN_ALIGN: NonZeroUsize = NonZeroUsize::new(1).unwrap();
type Err = AllocError;
fn allocate(
&self,
layout: Layout,
) -> Result<NonNull<[u8]>, Err>;
unsafe fn deallocate(
&self,
ptr: NonNull<u8>,
layout: Layout,
);
// Provided methods
unsafe fn reallocate(
&self,
ptr: NonNull<u8>,
old_layout: Layout,
new_layout: Layout,
) -> Result<NonNull<[u8]>, Err> { ... }
// as before, with `AllocError` similarly replaced w/ `Err`
}
unsafe trait Deallocator {
unsafe fn deallocate(&self, ptr: NonNull<u8>, layout: Layout);
}
impl<A: Allocator> Deallocator for A {
unsafe fn deallocate(&self, ptr: NonNull<u8>, layout: Layout) {
<Self as Allocator>::deallocate(self, ptr, layout)
}
}
/// The allocator is suitable for use as the global allocator.
unsafe trait GlobalAllocator: Allocator + Sync {
const REENTRANT_IN_STD: bool = true;
}
/// `Clone` will create a fungible (de)allocator (i.e. both
/// can deallocate the same memory), and `Copy` either is
/// the same as clone (i.e. `Clone` is a memcpy) or impossible
/// to implement.
unsafe trait AllocatorClone: Deallocator + Clone {}
/// Implementors must never incorrectly return `true`.
unsafe trait AllocatorCmp<Other: AllocatorCmp = Self>: Deallocator {
/// If `other` can free something, so can `self`.
fn can_free_like(&self, other: &Other) -> bool;
}
/// The allocator in question will not break `Pin` guarantees
/// even if subtyped with a shorter lifetime.
unsafe trait PinSafeAllocator: Allocator + 'static {}
unsafe trait DynAllocator {
/* current Allocator trait + `reallocate()` */
}
unsafe impl Allocator for dyn DynAllocator {
/* keep associated item defaults & forward methods */
}
unsafe impl !PinSafeAllocator for dyn DynAllocator {}
unsafe impl !AllocatorClone for dyn DynAllocator {}
impl<T, A, D> Box<T, D>
where
A: Allocator + AllocatorCmp<D>,
D: AllocatorCmp<A>,
{
// bikeshed better names
fn new_in_with(x: T, alloc: A, dealloc: D) -> Self {
if dealloc.can_free_like(&alloc) {
unsafe { Box::new_in_with_unchecked(...) }
}
}
fn with_dealloc(boxed: Box<T, A>, dealloc: D) -> Self { ... }
}
impl<T, A: PinSafeAllocator> Box<T, A> {
fn into_pin(boxed: Box<T, A>) -> Pin<Box<T, A>> { ... }
}
```