Skip to content

alloc: stabilise Allocator#156882

Draft
nia-e wants to merge 2 commits into
rust-lang:mainfrom
nia-e:stable-allocator
Draft

alloc: stabilise Allocator#156882
nia-e wants to merge 2 commits into
rust-lang:mainfrom
nia-e:stable-allocator

Conversation

@nia-e

@nia-e nia-e commented May 24, 2026

Copy link
Copy Markdown
Member

View all comments

Stabilise a bare-minimum (dyn-incompatible, but could be in the future) Allocator trait, alongside Box::new_in(), Vec::new_in(), the System & Global Allocators, and a blanket impl of Allocator for T: GlobalAlloc. For now, we should take care not to make it possible to instantiate anything other than a Vec or Box with custom allocators; it's Probably Fine, but worth a proper look before we rush in.

The soundness requirements for implementors were tightened to the most restrictive ones we could reasonably want per a conversation with @RalfJung.

This was discussed extensively at the all-hands with an apparent tentative consensus from libs and participating ecosystem stakeholders that the current design can be extended backwards-compatibly to address almost all usecases.

cc @rust-lang/libs @rust-lang/libs-api @rust-lang/opsem

r? libs


Edit, following more points being discovered: see the new stabilisation report

@rustbot rustbot added S-waiting-on-review Status: Awaiting review from the assignee but also interested parties. T-libs Relevant to the library team, which will review and decide on the PR/issue. labels May 24, 2026
@nia-e nia-e added A-allocators Area: Custom and system allocators relnotes Marks issues that should be documented in the release notes of the next release. S-waiting-on-fcp Status: PR is in FCP and is awaiting for FCP to complete. labels May 24, 2026
@nia-e nia-e added needs-fcp This change is insta-stable, or significant enough to need a team FCP to proceed. and removed S-waiting-on-fcp Status: PR is in FCP and is awaiting for FCP to complete. labels May 24, 2026
@nia-e

nia-e commented May 24, 2026

Copy link
Copy Markdown
Member Author

r? @Amanieu

@rustbot rustbot assigned Amanieu and unassigned Mark-Simulacrum May 24, 2026
@rust-log-analyzer

This comment has been minimized.

Comment thread library/core/src/alloc/mod.rs Outdated
@nia-e nia-e force-pushed the stable-allocator branch from ecf76bf to ed24b36 Compare May 24, 2026 17:42
Comment thread library/alloc/src/collections/binary_heap/mod.rs Outdated
Comment thread library/core/src/alloc/mod.rs Outdated
Comment thread library/core/src/alloc/global.rs Outdated
Comment thread tests/ui/allocator/not-an-allocator.u.stderr Outdated
Comment thread library/core/src/alloc/global.rs Outdated
Comment thread library/core/src/alloc/mod.rs Outdated
@theemathas

Copy link
Copy Markdown
Contributor

I believe the safety requirements are not yet correct. See #156544

@jmillikin

This comment has been minimized.

@bushrat011899

This comment has been minimized.

@jmillikin

This comment has been minimized.

@bushrat011899

This comment has been minimized.

@jmillikin

This comment has been minimized.

@bushrat011899

This comment has been minimized.

@joshtriplett

This comment was marked as outdated.

@rust-rfcbot

This comment was marked as outdated.

@matthieu-m

Copy link
Copy Markdown
Contributor

@nia-e With regard to NonNull<[u8]> (https://hackmd.io/nNHdKkp1TTK7jat0I-ABqA#NonNullltu8gt-return-type).

First of all, an alternative design is for Allocator to offer a method allowing querying the actual layout of a memory block, to post-facto recover the capacity (and over-alignment). Think fn layout_of(&self, _ptr: NonNull<u8>, layout: Layout) -> Layout { layout } (provided, specializable).

This has the advantage that only those who wish to use the excess capacity (if any) pay for the cost of recovering it. Or as per C++ motto: You Don't Pay For What You Don't Use.


With regard to the cost (or absence of cost) mentioned, I am not convinced the only issue is with dyn Allocator, and lack of inlining.

In the absence of a separate method to query the total/excess capacity, the only way for an implementation to convey the exact capacity is to return it from the get go. This means in turn that within the implementation the exact capacity must be passed through all layers, at all times.

The fact that no bloat is observed if allocate itself is inlined is nice... but it's doubtful, and generally undesirable, that allocate will be entirely inlined. For example, for a generic malloc implementation, allocation typically follows the following path:

  1. Hot Path (inline): if non-full slab available in thread-local storage, allocate from non-full slab.
  2. Warm Path (noinline): if no non-full slab available in thread-local storage, grab non-full slab from global storage, and allocate from it.
  3. Cold path (noinline): if no non-full slab available in global storage, ask OS for more memory.

The exact capacity must be conveyed through all layers, some of which are not inlined so they're out of the way in the hot path.

The only allocators where the entire allocation path can be inlined at no penalty are simple allocators like fixed-capacity arena allocators. All allocators with a split hot/other path will aim to mark the non-hot path as noinline to avoid bloating the hot path, specifically so the hot path can be inlined -- even a simple arena allocator with dynamic capacity.

NonNull<[u8]> risk bloating the inlined call to the non-hot function, which introduces bloat in all callers, even when the Allocator is a generic parameter and the outer allocate call is inlined.

@matthieu-m

This comment has been minimized.

@nia-e

nia-e commented May 31, 2026

Copy link
Copy Markdown
Member Author

@matthieu-m

The only allocators where the entire allocation path can be inlined at no penalty are simple allocators like fixed-capacity arena allocators.

I think this is a reason in favour of keeping the slice return type. Extremely simple allocators will be able to inline it away; for more complex ones, I'm doubtful that the extra pointer width is relevant. If an implementor wants to always return exactly the capacity it's asked for, it can make allocate a small #[inline] shim around its internal logic (which can return a pointer to u8) and set the size of the returned slice pointer directly from the layout. If not, it's not free, but the cost appears small enough that I don't expect it to be an issue. Having to do an extra method call to recover capacity is likely a much larger cost for usecases that need it, with the prime example here being the stdlib Vec.

If it comes to it, a similar wrapper trick can be done as with grow_in_place; callers would be free to pick between a definitely-inlined exact size slice allocation or a maybe-but-probably-not-inlined allocation that might return a larger slice. Then, users who don't care for these potential perf gains could just use whatever.

f my gay ass puppy life
@nia-e nia-e force-pushed the stable-allocator branch from 9d62ced to 331f145 Compare May 31, 2026 12:35
@rustbot

rustbot commented May 31, 2026

Copy link
Copy Markdown
Collaborator

This PR was rebased onto a different main commit. Here's a range-diff highlighting what actually changed.

Rebasing is a normal part of keeping PRs up to date, so no action is needed—this note is just to help reviewers.

@nia-e nia-e force-pushed the stable-allocator branch from 331f145 to f038322 Compare May 31, 2026 12:37
@rust-log-analyzer

Copy link
Copy Markdown
Collaborator

The job tidy failed! Check out the build log: (web) (plain enhanced) (plain)

Click to see the possible cause of the failure (guessed by this bot)
fmt: checked 6876 files
tidy check
tidy [rustdoc_json (src)]: `rustdoc-json-types` modified, checking format version
tidy: Skipping binary file check, read-only filesystem
tidy [style (tests)]: /checkout/tests/ui/lexer/crlf-in-byte-string-literal.rs: ignoring CR characters unnecessarily
tidy [style (tests)]: FAIL
removing old virtual environment
creating virtual environment at '/checkout/obj/build/venv' using 'python3.10' and 'venv'
creating virtual environment at '/checkout/obj/build/venv' using 'python3.10' and 'virtualenv'
Requirement already satisfied: pip in ./build/venv/lib/python3.10/site-packages (26.1.1)
linting python files
---
info: ES-Check: there were no ES version matching errors!  🎉
typechecking javascript files
tidy: The following check failed: style (tests)
Bootstrap failed while executing `test src/tools/tidy tidyselftest --extra-checks=py,cpp,js,spellcheck`
Command `/checkout/obj/build/x86_64-unknown-linux-gnu/stage1-tools-bin/rust-tidy --root-path=/checkout --cargo-path=/checkout/obj/build/x86_64-unknown-linux-gnu/stage0/bin/cargo --output-dir=/checkout/obj/build --concurrency=4 --npm-path=/node/bin/yarn --ci=true --extra-checks=py,cpp,js,spellcheck` failed with exit code 1
Created at: src/bootstrap/src/core/build_steps/tool.rs:1618:23
Executed at: src/bootstrap/src/core/build_steps/test.rs:1417:29

--- BACKTRACE vvv
   0: <bootstrap::utils::exec::DeferredCommand>::finish_process
             at /checkout/src/bootstrap/src/utils/exec.rs:939:17
   1: <bootstrap::utils::exec::DeferredCommand>::wait_for_output::<&bootstrap::utils::exec::ExecutionContext>
             at /checkout/src/bootstrap/src/utils/exec.rs:831:21
   2: <bootstrap::utils::exec::ExecutionContext>::run
             at /checkout/src/bootstrap/src/utils/exec.rs:741:45
   3: <bootstrap::utils::exec::BootstrapCommand>::run::<&bootstrap::core::builder::Builder>
             at /checkout/src/bootstrap/src/utils/exec.rs:339:27
   4: <bootstrap::core::build_steps::test::Tidy as bootstrap::core::builder::Step>::run
             at /checkout/src/bootstrap/src/core/build_steps/test.rs:1417:29
   5: <bootstrap::core::builder::Builder>::ensure::<bootstrap::core::build_steps::test::Tidy>
             at /checkout/src/bootstrap/src/core/builder/mod.rs:1595:36
   6: <bootstrap::core::build_steps::test::Tidy as bootstrap::core::builder::Step>::make_run
             at /checkout/src/bootstrap/src/core/build_steps/test.rs:1339:21
   7: <bootstrap::core::builder::StepDescription>::maybe_run
             at /checkout/src/bootstrap/src/core/builder/mod.rs:476:13
   8: bootstrap::core::builder::cli_paths::match_paths_to_steps_and_run
             at /checkout/src/bootstrap/src/core/builder/cli_paths.rs:232:18
   9: <bootstrap::core::builder::Builder>::run_step_descriptions
             at /checkout/src/bootstrap/src/core/builder/mod.rs:1138:9
  10: <bootstrap::core::builder::Builder>::execute_cli
             at /checkout/src/bootstrap/src/core/builder/mod.rs:1117:14
  11: <bootstrap::Build>::build
             at /checkout/src/bootstrap/src/lib.rs:803:25
  12: bootstrap::main
             at /checkout/src/bootstrap/src/bin/main.rs:130:11
  13: <fn() as core::ops::function::FnOnce<()>>::call_once
             at /rustc/ef0fb8a2563200e322fa4419f09f65a63742038c/library/core/src/ops/function.rs:250:5
  14: std::sys::backtrace::__rust_begin_short_backtrace::<fn(), ()>
             at /rustc/ef0fb8a2563200e322fa4419f09f65a63742038c/library/std/src/sys/backtrace.rs:166:18
  15: std::rt::lang_start::<()>::{closure#0}
             at /rustc/ef0fb8a2563200e322fa4419f09f65a63742038c/library/std/src/rt.rs:206:18
  16: <&dyn core::ops::function::Fn<(), Output = i32> + core::marker::Sync + core::panic::unwind_safe::RefUnwindSafe as core::ops::function::FnOnce<()>>::call_once
             at /rustc/ef0fb8a2563200e322fa4419f09f65a63742038c/library/core/src/ops/function.rs:287:21
  17: std::panicking::catch_unwind::do_call::<&dyn core::ops::function::Fn<(), Output = i32> + core::marker::Sync + core::panic::unwind_safe::RefUnwindSafe, i32>
             at /rustc/ef0fb8a2563200e322fa4419f09f65a63742038c/library/std/src/panicking.rs:581:40
  18: std::panicking::catch_unwind::<i32, &dyn core::ops::function::Fn<(), Output = i32> + core::marker::Sync + core::panic::unwind_safe::RefUnwindSafe>
             at /rustc/ef0fb8a2563200e322fa4419f09f65a63742038c/library/std/src/panicking.rs:544:19
  19: std::panic::catch_unwind::<&dyn core::ops::function::Fn<(), Output = i32> + core::marker::Sync + core::panic::unwind_safe::RefUnwindSafe, i32>
             at /rustc/ef0fb8a2563200e322fa4419f09f65a63742038c/library/std/src/panic.rs:359:14
  20: std::rt::lang_start_internal::{closure#0}
             at /rustc/ef0fb8a2563200e322fa4419f09f65a63742038c/library/std/src/rt.rs:175:24
  21: std::panicking::catch_unwind::do_call::<std::rt::lang_start_internal::{closure#0}, isize>
             at /rustc/ef0fb8a2563200e322fa4419f09f65a63742038c/library/std/src/panicking.rs:581:40
---
  28: __libc_start_main
  29: _start


Command has failed. Rerun with -v to see more details.
Build completed unsuccessfully in 0:03:01
  local time: Sun May 31 12:44:23 UTC 2026
  network time: Sun, 31 May 2026 12:44:23 GMT
##[error]Process completed with exit code 1.
##[group]Run echo "disk usage:"

@cuviper

cuviper commented May 31, 2026

Copy link
Copy Markdown
Member

@matthieu-m

You can ignore the alignment of the allocator type in such a case (#[repr(packed)]) since the allocator-in-the-allocation is never used directly, which is nice.

We do have cases that need the allocator directly though, e.g. unstable fn allocator(this) -> &A, and stable fn make_mut(this) -> &mut T needs a new allocation when shared. (It's fine if that A: Clone refers to something new though, so we still don't need a safety invariant on clone.)

@maxdexh

maxdexh commented May 31, 2026

Copy link
Copy Markdown
Contributor

I think #155746 should be fixed before this is stabilized.

Edit: Also #156490

#[unstable(feature = "allocator_api", issue = "32838")]
#[stable(feature = "allocator_api", since = "CURRENT_RUSTC_VERSION")]
#[derive(Copy, Clone, PartialEq, Eq, Debug)]
pub struct AllocError;

@bushrat011899 bushrat011899 Jun 1, 2026

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Asked on Zulip but mentioning here for clarity: should AllocError be #[non_exhaustive] (with some constructor function or public constant) to leave open the possibility of more detailed error reporting in the future? For Allocator::allocate it's pretty clear the only error that could occur is OOM, but for grow/etc. or other future methods there might be useful information that an allocator could return.

I believe #[non_exhaustive] can be removed without a breaking change, so aside from providing a default constructor I don't think there's any downsides to being conservative.

View changes since the review

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

AllocError being a Zero-Sized Type (ZST) is a feature, not a bug.

Specifically, it being a ZST is the only reason that Result<NonNull<[u8]>, AllocError> is only two pointers wide: there's a single niche value (null), which only a ZST error can fit it.

Richer error types should be provided by other means, for example by making the error type of Allocator customizable (type Error: Into<AllocError>; would work well).

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Specifically, it being a ZST is the only reason that Result<NonNull<[u8]>, AllocError> is only two pointers wide: there's a single niche value (null), which only a ZST error can fit it.

That's not correct, Result<NonNull<[u8]>, *const ()> is also two pointers wide (though that's not guaranteed of course):
https://play.rust-lang.org/?version=stable&mode=debug&edition=2024&gist=f57891eefbf603b1719ae3c9bd725206

NonNull<[u8]> has a niche where the pointer part is null, and the length part can be anything, so the Err variant has the Ok variant's pointer part be null, and the length part's space is used for the *const () error value.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Right, you are correct.

I'm still hoping to get a result of Result<NonNull<u8>, AllocError> at which point only a ZST does the job.

@nia-e

nia-e commented Jun 1, 2026

Copy link
Copy Markdown
Member Author

Given the feedback here & on Zulip, the new design for allocator_api probably needs some time to bake & iron out soundness bugs. I'll be keeping the previous document up-to-date w/ any changes or updates, but it likely makes sense to first land these changes unstably and then see if it holds up to scrutiny. I do think something could be stabilised soon-ish, but there won't be any harm in waiting a bit ^^

edit: the conversation will mainly continue on zulip and on the issues filed in response to this PR; if you have concerns not yet addressed, please ping me there and i'll happily look into seeing if the design can be adapted

@rustbot author

@nia-e nia-e removed the I-libs-api-nominated Nominated for discussion during a libs-api team meeting. label Jun 1, 2026
@nia-e nia-e marked this pull request as draft June 1, 2026 10:51
@maxdexh

This comment was marked as off-topic.

@nia-e

This comment was marked as off-topic.

@rust-bors

rust-bors Bot commented Jun 2, 2026

Copy link
Copy Markdown
Contributor

☔ The latest upstream changes (presumably #157303) made this pull request unmergeable. Please resolve the merge conflicts.

JonathanBrouwer added a commit to JonathanBrouwer/rust that referenced this pull request Jul 8, 2026
allow `Allocator`s to be used as `#[global_allocator]`s

The (hopefully) immanent stabilisation of the `Allocator` trait raises the question of what is to be done about the older, already-stable `GlobalAlloc` trait. In my opinion, having two nearly-identical traits for the same purpose is needlessly confusing. Going forward, `Allocator` as the more modern interface should be _the_ allocator trait.

With `Allocator` being currently unstable, there is the possibility of implementing `GlobalAlloc` for all `Allocator`s, thereby allowing them to be used as `#[global_allocator]` and allowing crates to seamlessly (and semver-compatibly) switch to `Allocator`. However, unconditionally implementing `GlobalAlloc` presents a footgun to users, as e.g. using `Global` as `#[global_allocator]` will lead to infinite recursion. @nia-e initially tried to resolve this in e1b7097 (rust-lang#156882) by using weird trait trickery to implement `GlobalAlloc` for every allocator except `Global`. But this does not go far enough, e.g. a bump allocator that itself allocates from `Global` is similarly unsuitable as global allocator.

Thus, with this PR, I'd like to propose adding a new marker trait for allocators that can be used as `#[global_allocator]`:
```rust
// in core::alloc

trait GlobalAllocator: Allocator {}
```
`GlobalAlloc` can then be implemented for all `GlobalAllocator`s:
```rust
impl<A> GlobalAlloc for A
where
    A: GlobalAllocator
{
    /* ... */
}
```

This provides a backwards-compatible way for allocator libraries to switch to the new interface and allows deprecating `GlobalAlloc` (not done here). Over time, I expect that `GlobalAlloc` will become more and more of an implementation detail of the `#[global_allocator]` macro (for instance, one might add perma-unstable, hidden methods for things like `grow_zeroed` that are customised only by the blanket implementation).

With regards to naming, I chose `GlobalAllocator` to mirror `Allocator`. `GlobalAlloc` should probably be deprecated quickly after stabilising `GlobalAllocator` to avoid confusion. For the same reason, I think it'd be better to add `GlobalAllocator` before stabilising `Allocator` – but that is not a necessity.

r? @nia-e
@rustbot label +I-libs-api-nominated
JonathanBrouwer added a commit to JonathanBrouwer/rust that referenced this pull request Jul 8, 2026
allow `Allocator`s to be used as `#[global_allocator]`s

The (hopefully) immanent stabilisation of the `Allocator` trait raises the question of what is to be done about the older, already-stable `GlobalAlloc` trait. In my opinion, having two nearly-identical traits for the same purpose is needlessly confusing. Going forward, `Allocator` as the more modern interface should be _the_ allocator trait.

With `Allocator` being currently unstable, there is the possibility of implementing `GlobalAlloc` for all `Allocator`s, thereby allowing them to be used as `#[global_allocator]` and allowing crates to seamlessly (and semver-compatibly) switch to `Allocator`. However, unconditionally implementing `GlobalAlloc` presents a footgun to users, as e.g. using `Global` as `#[global_allocator]` will lead to infinite recursion. @nia-e initially tried to resolve this in e1b7097 (rust-lang#156882) by using weird trait trickery to implement `GlobalAlloc` for every allocator except `Global`. But this does not go far enough, e.g. a bump allocator that itself allocates from `Global` is similarly unsuitable as global allocator.

Thus, with this PR, I'd like to propose adding a new marker trait for allocators that can be used as `#[global_allocator]`:
```rust
// in core::alloc

trait GlobalAllocator: Allocator {}
```
`GlobalAlloc` can then be implemented for all `GlobalAllocator`s:
```rust
impl<A> GlobalAlloc for A
where
    A: GlobalAllocator
{
    /* ... */
}
```

This provides a backwards-compatible way for allocator libraries to switch to the new interface and allows deprecating `GlobalAlloc` (not done here). Over time, I expect that `GlobalAlloc` will become more and more of an implementation detail of the `#[global_allocator]` macro (for instance, one might add perma-unstable, hidden methods for things like `grow_zeroed` that are customised only by the blanket implementation).

With regards to naming, I chose `GlobalAllocator` to mirror `Allocator`. `GlobalAlloc` should probably be deprecated quickly after stabilising `GlobalAllocator` to avoid confusion. For the same reason, I think it'd be better to add `GlobalAllocator` before stabilising `Allocator` – but that is not a necessity.

r? @nia-e
@rustbot label +I-libs-api-nominated
JonathanBrouwer added a commit to JonathanBrouwer/rust that referenced this pull request Jul 8, 2026
allow `Allocator`s to be used as `#[global_allocator]`s

The (hopefully) immanent stabilisation of the `Allocator` trait raises the question of what is to be done about the older, already-stable `GlobalAlloc` trait. In my opinion, having two nearly-identical traits for the same purpose is needlessly confusing. Going forward, `Allocator` as the more modern interface should be _the_ allocator trait.

With `Allocator` being currently unstable, there is the possibility of implementing `GlobalAlloc` for all `Allocator`s, thereby allowing them to be used as `#[global_allocator]` and allowing crates to seamlessly (and semver-compatibly) switch to `Allocator`. However, unconditionally implementing `GlobalAlloc` presents a footgun to users, as e.g. using `Global` as `#[global_allocator]` will lead to infinite recursion. @nia-e initially tried to resolve this in e1b7097 (rust-lang#156882) by using weird trait trickery to implement `GlobalAlloc` for every allocator except `Global`. But this does not go far enough, e.g. a bump allocator that itself allocates from `Global` is similarly unsuitable as global allocator.

Thus, with this PR, I'd like to propose adding a new marker trait for allocators that can be used as `#[global_allocator]`:
```rust
// in core::alloc

trait GlobalAllocator: Allocator {}
```
`GlobalAlloc` can then be implemented for all `GlobalAllocator`s:
```rust
impl<A> GlobalAlloc for A
where
    A: GlobalAllocator
{
    /* ... */
}
```

This provides a backwards-compatible way for allocator libraries to switch to the new interface and allows deprecating `GlobalAlloc` (not done here). Over time, I expect that `GlobalAlloc` will become more and more of an implementation detail of the `#[global_allocator]` macro (for instance, one might add perma-unstable, hidden methods for things like `grow_zeroed` that are customised only by the blanket implementation).

With regards to naming, I chose `GlobalAllocator` to mirror `Allocator`. `GlobalAlloc` should probably be deprecated quickly after stabilising `GlobalAllocator` to avoid confusion. For the same reason, I think it'd be better to add `GlobalAllocator` before stabilising `Allocator` – but that is not a necessity.

r? @nia-e
@rustbot label +I-libs-api-nominated
jhpratt added a commit to jhpratt/rust that referenced this pull request Jul 8, 2026
allow `Allocator`s to be used as `#[global_allocator]`s

The (hopefully) immanent stabilisation of the `Allocator` trait raises the question of what is to be done about the older, already-stable `GlobalAlloc` trait. In my opinion, having two nearly-identical traits for the same purpose is needlessly confusing. Going forward, `Allocator` as the more modern interface should be _the_ allocator trait.

With `Allocator` being currently unstable, there is the possibility of implementing `GlobalAlloc` for all `Allocator`s, thereby allowing them to be used as `#[global_allocator]` and allowing crates to seamlessly (and semver-compatibly) switch to `Allocator`. However, unconditionally implementing `GlobalAlloc` presents a footgun to users, as e.g. using `Global` as `#[global_allocator]` will lead to infinite recursion. @nia-e initially tried to resolve this in e1b7097 (rust-lang#156882) by using weird trait trickery to implement `GlobalAlloc` for every allocator except `Global`. But this does not go far enough, e.g. a bump allocator that itself allocates from `Global` is similarly unsuitable as global allocator.

Thus, with this PR, I'd like to propose adding a new marker trait for allocators that can be used as `#[global_allocator]`:
```rust
// in core::alloc

trait GlobalAllocator: Allocator {}
```
`GlobalAlloc` can then be implemented for all `GlobalAllocator`s:
```rust
impl<A> GlobalAlloc for A
where
    A: GlobalAllocator
{
    /* ... */
}
```

This provides a backwards-compatible way for allocator libraries to switch to the new interface and allows deprecating `GlobalAlloc` (not done here). Over time, I expect that `GlobalAlloc` will become more and more of an implementation detail of the `#[global_allocator]` macro (for instance, one might add perma-unstable, hidden methods for things like `grow_zeroed` that are customised only by the blanket implementation).

With regards to naming, I chose `GlobalAllocator` to mirror `Allocator`. `GlobalAlloc` should probably be deprecated quickly after stabilising `GlobalAllocator` to avoid confusion. For the same reason, I think it'd be better to add `GlobalAllocator` before stabilising `Allocator` – but that is not a necessity.

r? @nia-e
@rustbot label +I-libs-api-nominated
jhpratt added a commit to jhpratt/rust that referenced this pull request Jul 9, 2026
allow `Allocator`s to be used as `#[global_allocator]`s

The (hopefully) immanent stabilisation of the `Allocator` trait raises the question of what is to be done about the older, already-stable `GlobalAlloc` trait. In my opinion, having two nearly-identical traits for the same purpose is needlessly confusing. Going forward, `Allocator` as the more modern interface should be _the_ allocator trait.

With `Allocator` being currently unstable, there is the possibility of implementing `GlobalAlloc` for all `Allocator`s, thereby allowing them to be used as `#[global_allocator]` and allowing crates to seamlessly (and semver-compatibly) switch to `Allocator`. However, unconditionally implementing `GlobalAlloc` presents a footgun to users, as e.g. using `Global` as `#[global_allocator]` will lead to infinite recursion. @nia-e initially tried to resolve this in e1b7097 (rust-lang#156882) by using weird trait trickery to implement `GlobalAlloc` for every allocator except `Global`. But this does not go far enough, e.g. a bump allocator that itself allocates from `Global` is similarly unsuitable as global allocator.

Thus, with this PR, I'd like to propose adding a new marker trait for allocators that can be used as `#[global_allocator]`:
```rust
// in core::alloc

trait GlobalAllocator: Allocator {}
```
`GlobalAlloc` can then be implemented for all `GlobalAllocator`s:
```rust
impl<A> GlobalAlloc for A
where
    A: GlobalAllocator
{
    /* ... */
}
```

This provides a backwards-compatible way for allocator libraries to switch to the new interface and allows deprecating `GlobalAlloc` (not done here). Over time, I expect that `GlobalAlloc` will become more and more of an implementation detail of the `#[global_allocator]` macro (for instance, one might add perma-unstable, hidden methods for things like `grow_zeroed` that are customised only by the blanket implementation).

With regards to naming, I chose `GlobalAllocator` to mirror `Allocator`. `GlobalAlloc` should probably be deprecated quickly after stabilising `GlobalAllocator` to avoid confusion. For the same reason, I think it'd be better to add `GlobalAllocator` before stabilising `Allocator` – but that is not a necessity.

r? @nia-e
@rustbot label +I-libs-api-nominated
JonathanBrouwer added a commit to JonathanBrouwer/rust that referenced this pull request Jul 9, 2026
allow `Allocator`s to be used as `#[global_allocator]`s

The (hopefully) immanent stabilisation of the `Allocator` trait raises the question of what is to be done about the older, already-stable `GlobalAlloc` trait. In my opinion, having two nearly-identical traits for the same purpose is needlessly confusing. Going forward, `Allocator` as the more modern interface should be _the_ allocator trait.

With `Allocator` being currently unstable, there is the possibility of implementing `GlobalAlloc` for all `Allocator`s, thereby allowing them to be used as `#[global_allocator]` and allowing crates to seamlessly (and semver-compatibly) switch to `Allocator`. However, unconditionally implementing `GlobalAlloc` presents a footgun to users, as e.g. using `Global` as `#[global_allocator]` will lead to infinite recursion. @nia-e initially tried to resolve this in e1b7097 (rust-lang#156882) by using weird trait trickery to implement `GlobalAlloc` for every allocator except `Global`. But this does not go far enough, e.g. a bump allocator that itself allocates from `Global` is similarly unsuitable as global allocator.

Thus, with this PR, I'd like to propose adding a new marker trait for allocators that can be used as `#[global_allocator]`:
```rust
// in core::alloc

trait GlobalAllocator: Allocator {}
```
`GlobalAlloc` can then be implemented for all `GlobalAllocator`s:
```rust
impl<A> GlobalAlloc for A
where
    A: GlobalAllocator
{
    /* ... */
}
```

This provides a backwards-compatible way for allocator libraries to switch to the new interface and allows deprecating `GlobalAlloc` (not done here). Over time, I expect that `GlobalAlloc` will become more and more of an implementation detail of the `#[global_allocator]` macro (for instance, one might add perma-unstable, hidden methods for things like `grow_zeroed` that are customised only by the blanket implementation).

With regards to naming, I chose `GlobalAllocator` to mirror `Allocator`. `GlobalAlloc` should probably be deprecated quickly after stabilising `GlobalAllocator` to avoid confusion. For the same reason, I think it'd be better to add `GlobalAllocator` before stabilising `Allocator` – but that is not a necessity.

r? @nia-e
@rustbot label +I-libs-api-nominated
JonathanBrouwer added a commit to JonathanBrouwer/rust that referenced this pull request Jul 9, 2026
allow `Allocator`s to be used as `#[global_allocator]`s

The (hopefully) immanent stabilisation of the `Allocator` trait raises the question of what is to be done about the older, already-stable `GlobalAlloc` trait. In my opinion, having two nearly-identical traits for the same purpose is needlessly confusing. Going forward, `Allocator` as the more modern interface should be _the_ allocator trait.

With `Allocator` being currently unstable, there is the possibility of implementing `GlobalAlloc` for all `Allocator`s, thereby allowing them to be used as `#[global_allocator]` and allowing crates to seamlessly (and semver-compatibly) switch to `Allocator`. However, unconditionally implementing `GlobalAlloc` presents a footgun to users, as e.g. using `Global` as `#[global_allocator]` will lead to infinite recursion. @nia-e initially tried to resolve this in e1b7097 (rust-lang#156882) by using weird trait trickery to implement `GlobalAlloc` for every allocator except `Global`. But this does not go far enough, e.g. a bump allocator that itself allocates from `Global` is similarly unsuitable as global allocator.

Thus, with this PR, I'd like to propose adding a new marker trait for allocators that can be used as `#[global_allocator]`:
```rust
// in core::alloc

trait GlobalAllocator: Allocator {}
```
`GlobalAlloc` can then be implemented for all `GlobalAllocator`s:
```rust
impl<A> GlobalAlloc for A
where
    A: GlobalAllocator
{
    /* ... */
}
```

This provides a backwards-compatible way for allocator libraries to switch to the new interface and allows deprecating `GlobalAlloc` (not done here). Over time, I expect that `GlobalAlloc` will become more and more of an implementation detail of the `#[global_allocator]` macro (for instance, one might add perma-unstable, hidden methods for things like `grow_zeroed` that are customised only by the blanket implementation).

With regards to naming, I chose `GlobalAllocator` to mirror `Allocator`. `GlobalAlloc` should probably be deprecated quickly after stabilising `GlobalAllocator` to avoid confusion. For the same reason, I think it'd be better to add `GlobalAllocator` before stabilising `Allocator` – but that is not a necessity.

r? @nia-e
@rustbot label +I-libs-api-nominated
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

A-allocators Area: Custom and system allocators A-run-make Area: port run-make Makefiles to rmake.rs needs-fcp This change is insta-stable, or significant enough to need a team FCP to proceed. relnotes Marks issues that should be documented in the release notes of the next release. S-waiting-on-author Status: This is awaiting some action (such as code changes or more information) from the author. T-clippy Relevant to the Clippy team. T-libs Relevant to the library team, which will review and decide on the PR/issue. T-rust-analyzer Relevant to the rust-analyzer team, which will review and decide on the PR/issue.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

dyn Allocator together with Allocator + Clone requirements is unsound, leading to UB with Arc