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
    # State of Allocators (allhands '26) ## tl;dr Can we stabilise anything now? - I think yes, the trait itself at least - Could go together with a couple methods on `Box`/collections just to make it useful - Having a parallel allocator-generic list of methods on all collections probably needs more design consideration ## Current trait ```rust pub 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> { ... } fn by_ref(&self) -> &Self where Self: Sized { ... } } ``` Bikeshedded extra stuff ```rust // Document that impl'ing PartialEq for Allocator means allocating with one // allows freeing with the other trait Allocator { #[unstable(whatever)] fn dyn_incompatible_dont_use_me<T>() {} #[unstable(whatever)] fn by_ref() } impl<T: Allocator> GlobalAlloc for T { /* ... */ } // -- todo later maybe -- trait Allocator { final fn by_ref(...); fn reallocate(...) { if new_layout > old_layout { self.grow() } else { self.shrink() } } } trait AllocatorEq: Allocator { fn bikeshed_me<A: AllocatorEq>(&self, other: &A) -> Something /* bool? Option<bool>? */ { // default? } } ``` ## Past attempts A lot of folks have wanted stable allocators and tried to get this done by deciding to do a "final bikeshed round" to bring in all the changes they want. This was attempted at the last all-hands also, for instance. I am going to do the opposite and instead try to convince you to *stop* bikeshedding because what we have is Workable and Good. ## Why now It has been about a decade since allocators were accepted (https://github.com/rust-lang/rfcs/pull/1398) and progress has slowed massively lately. Most discussion has been stalling and energy has gone into much larger overhauls that are unlikely to be merged (e.g. Store API). Stabilising *something* (e.g. the trait itself) could drive ecosystem adoption, and stabilising it (nearly) as-is would be nice as it can be done quickly without us losing out on much flexibility. Clearly the progress per unit of time spent on allocator has been nearing zero - bikeshedding this more won't get us much further unless there's some fundamental rework that we had missed all along. It would be better to spend effort where there are far more outstanding concerns, namely the actual API we want on collections. ## Prior art Zig has much simpler allocators than us: - https://github.com/ziglang/zig/blob/master/lib/std/mem/Allocator.zig C++ has this also which is at a similar complexity level: - https://en.cppreference.com/cpp/memory/allocator ## Existing points of contention - Use of `NonZeroLayout` instead of `Layout` (i.e. `Layout` but with size != 0) - Certain allocators don't like this; e.g. `jemalloc`'s internal allocation method - This could allow us to simplify logic in collection types but only if `Allocator` was `const` (or `new()` was non-`const`) which is a whole other can of worms - Having `NonZeroLayout` means the check for zero-sizedness would be on the caller side where it might be optimised away better? - However, this is only very rarely an actual issue (most allocators *can* handle zero-sized allocations) and this is extra API complexity - There was the idea of having an associated constant for `SUPPORTS_ZERO_SIZE` or similar & make `allocate` unsafe - https://github.com/rust-lang/libs-team/issues/770 - Split `Deallocator` trait - `trait Allocator: Deallocator {...}` - In certain cases (e.g. bump allocators), deallocation requires less info than allocation or is even a no-op - It *is* a decent bit of extra complexity in the API and requires 2 traits be implemented which is marginally sad for ergonomics - Alternatively, we can stabilise `Allocator` as-is and defer the details for later (see my comment on github) - This could be done more neatly with supertrait auto impl in the future, but switching to that later should be non-breaking also - This would also probably require a lot of API bikeshedding on how to relax a `Collection<T, A: Allocator>` to `A: Deallocator` - https://github.com/rust-lang/libs-team/issues/769 - Break dyn compatibility - Allows for an associated `AllocError` type - Allocator equality comparison (`PartialEq` supertrait) is a thing people want too apparently? - Rust for Linux might like some associated constants too it seems? - Doesn't necessarily seem like these are blocking things for them, though - An alternative was proposed to make a boutique `DynAllocator` type that elides the associated types and constants - However, this means you're forced to monomorphise anything generic over the allocator... yikes - It would also mean every allocator ever has to provide at least placeholder values for every random constant, etc. - https://rust-lang.zulipchat.com/#narrow/channel/197181-t-libs.2Fwg-allocators/topic/Do.20we.20really.20need.20object-safety.20.2F.20.60dyn.20Allocator.60/ - (also more API complexity) - Just do a big overhaul (e.g. `Store`) - Apparently this could be done backwards-compatibly in the future anyways, yay! - Also many of these proposals don't fix most of the points above - https://shift.click/blog/allocator-trait-talk/#addendum-what-about-the-store-api - https://cetra3.github.io/blog/state-of-allocators-2026/ ## Proposal Stabilise the `Allocator` trait as-is. Allow for some time to experiment with the concrete APIs we want, but likely we'll end up stabilising at least `reserve` & such. A better API would probably require defaults to be considered in inference, but that might be a ways off so we can consider stabilising a simpler API in the meantime (likely `try_reserve` at least). ## Notes Note-taker: Crystal Durham \<cad97@cad97.com\> \<crystal.durham@canonical.com\> - Had Allocator for 10 years, never stable, bikeshed everything, stabilize something - Go through the trait item by item - Attempted to "last bikeshed" at last all-hands - API depends on what types team gives us (e.g. defaults impact inference) - Zig allocators are simpler (too simple), C++ is a similar complexity, C is just `realloc` - Goal: stabilize *something* for the Allocator trait - Better API requires better inference, can be added backwards-compatibly - RfL: Nees a way to pass (allocator-specific) flags to the allocator - Only on allocate, doesn't change dealloc - Utilize a context/capabilities mechanism? - Reinterpret the allocator with a different type for flags? - Transmute is reachable soonest, context is far away - e.g. `unsafe fn Vec::push_with_allocator` - Also allows sharing allocators between collections - (post-scriptum by Crystal) Please always use the same allocator type for storage :pleading_face: - Trait for changing allocator on a container? - Probably out of scope for now - Lots of alternative allocators in the ecosystem - Allocator libraries often don't copy std fixes - Must support bumpalo - Wants `Deallocator` trait for performance - "Allocator" is reference-to-arena - Want `PartialEq` for Allocator - Do the allocators share an allocator pool - Probably be better with a dedicated method - Might be misleading - Problems with `dyn` usage - Needs to be there from the start? - `false` is the wrong default for copies of an allocator - Unidirectional in the kernel - kmalloc can be put in kvmalloc, but not the reverse - `LinkedList::append` needs `AllocatorEq::same_pool` - DECIDED: doesn't need to be a supertrait, can be put off - Add docs: "If you `PartialEq`, partial_eq means interchangable allocation" - `AllocatorWithFlags` works backwards-compatibly with supertrait shadowing and auto-impl - See below - Breaking `dyn` compatibility... - Allows `AllocError` type - What is the use-case - Saying something other than "can't handle this request" - `PartialEq` is not dyn-saf - Deferred - `DynAllocator` can handle the tricky bits - DECIDED: `Allocator` trait will remain just normal code - QuestDB wants to know the soft limit that caused an error (but our error doesn't carry data) - We think they should do the error reporting inside the allocator, not outside - Or passing an outvar into the allocator - `dyn Allocator` is better than custom error types - Allocator description constants - e.g. `MIN_ALIGN`, `CAN_SKIP_REALIGN`, `NOP_DEALLOCATION`, `ZST_ALLOC_IS_DANGLING` - Put these into the vtable? (lang requirement) - But not constant anymore - Breaks the invariant that `dyn Trait: Trait` - Wants access to the constants as the conservative option when using `dyn Allocator` - Consensus: Description constants should go onto a subtrait - Deallocator split - Can be backwards compatible: `Allocator: Deallocator` - Allocator returns `NonNull<[u8]>` - If inlined, does calculating that size get properly optimized out? - We hope so - `Store` will indeed be backwards compatibly - `NonZeroLayout` - Ugly logic for `Vec::new` etc because it *needs* to use `ptr::dangling` - Allocator might still want to track ZST allocations (weak argument) - According to Oli: const traits are *reasonably* close (modulo syntax bikeshedding) - Why that won't work: - `Box<[ZST; N]> -> Box<[ZST]> -> Vec<ZST>` - Standard collections can keep the extra handling - Const traits can potentially simplify new collections - `Global` can do the zero sized checking - DECIDED: We're using `Layout` - In-place realloc - We can do this by passing flags thru the idea discussed above - Back to associated constants - `const_eval_select` on if the thing is provided constant - DECIDED: Mark as not-dyn-compatible for now, but otherwise stay dyn-safe - e.g. Perma-unstable method `Allocator::__block_dyn_compatibility<T>()` - DECIDED: Required before stabilization - `impl<A: Allocator> GlobalAlloc for A` - Double-check if `?Sized` bound is needed - Maybe: - `fn realloc` with default body calling `grow`/`shrink` - This is the better pit-of-success default direction - DECIDED: defer stabilizing `fn by_ref` - Also want stabilization: - `Box::new_in` - Conversions imply also `Arc`, `Rc` - `Vec::new_in` - Conversions imply also `String` - Audit any allocator-generic conversions away from stabilized `new_in` - Needs reservation impls / dummy trait bound - `Allocator for String` will require an edition change - FCP ASAP :pleading_face::point_right::point_left: - Final issue triage - Name explosion continues to be annoying - Future problem but needs to be handled soon™ See Also: https://github.com/rust-lang/wg-allocators/issues/106 ## Alice: potential way to add flags in the future if we stabilize current trait. ```rust pub unsafe trait AllocatorWithFlags { type ExtraArgs; // argument splatting makes it "optional" arguments // Required methods fn allocate(&self, layout: Layout, args: ExtraArgs) -> Result<NonNull<[u8]>, AllocError>; unsafe fn deallocate(&self, ptr: NonNull<u8>, layout: Layout); } pub unsafe trait Allocator: AllocatorWithFlags<ExtraArgs=()> { // Required methods fn allocate(&self, layout: Layout) -> Result<NonNull<[u8]>, AllocError>; unsafe fn deallocate(&self, ptr: NonNull<u8>, layout: Layout); } ```

    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