Nia
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
    • Invite by email
      Invitee

      This note has no invitees

    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note No publishing access yet

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.

      Your account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

      Your team account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

      Explore these features while you wait
      Complete general settings
      Bookmark and like published notes
      Write a few more notes
      Complete general settings
      Write a few more notes
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Note Insights New
    • Make a copy
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Note Insights Versions and GitHub Sync Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Make a copy Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
  • Invite by email
    Invitee

    This note has no invitees

  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note No publishing access yet

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.

    Your account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

    Your team account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

    Explore these features while you wait
    Complete general settings
    Bookmark and like published notes
    Write a few more notes
    Complete general settings
    Write a few more notes
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       Owned this note    Owned this note      
    Published Linked with GitHub
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    # 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>> { ... } } ```

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password
    or
    Sign in via Google Sign in via Facebook Sign in via X(Twitter) Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    By signing in, you agree to our terms of service.

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully