rust-lang / rust-lang/libs-team

add a way to reuse a `Box` allocation

Open
#857 14 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

api-change-proposal
Dominant language
Rust
Stars
178
Forks
28
Avg merge
15m
Merged PRs (30d)
1

Description

Proposal

Problem statement

Add two associated functions for recovering the allocation from a Box<T, A> or Pin<Box<T, A>> while dropping the value in place.

Motivating examples or use cases

In my unpublished hobby kernel, I'm using intrusive data structures (wavltree to be precise) to store notification interest lists in the scheduler. As is common with intrusiveness, the nodes are !Unpin and need to be pinned in memory to be usable. At the same time, all memory has to be allocated ahead of time, I cannot just use Box::pin to create new nodes. While the creation of new nodes in an existing allocation is possible using Box::write, I also need a way to recover the allocation (expressed as Box<MaybeUninit<T>>) from a Pin<Box<T>> while dropping the T.

Solution sketch

Add drop as an associated function to Box that acts similar to Box::take, but only returns the allocation and drops the value in place. drop_pinned performs the same operation, but for pinned boxes. The requirements of Pin are upheld as the inner value is dropped before the allocation is reused.

// in alloc::boxed

impl<T, A: Allocator> Box<T, A> {
    pub fn drop(this: Box<T, A>) -> Box<MaybeUninit<T>, A>;
    pub fn drop_pinned(this: Pin<Box<T, A>>) -> Box<MaybeUninit<T>, A>;
}

Alternatives

It is possible to write helper functions that do this in user code.

Links and related work

Contributor guide

No contributing guide indexed for this repository

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start in the alloc::boxed module and compare the proposed functions with the existing Box::take and Box::write APIs. Trace how Box and Pin<Box> ownership and dropping are handled, then review the related standard-library tests. Done means the API design is agreed and its allocation-reuse and pinned-drop behavior are covered by tests.

Written by the indexing model from the issue text.

Assessment

Tech stack
rust
Domain
backend-api-design
Issue type
Feature
Difficulty
5/5
Estimated time
Over a week
Activity status
Active
Clarity
Mostly clear
Newbie friendliness
45/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.