rust-lang / rust-lang/rfcs

Possibility of exposing `RcBox` for transferring allocations between `Box` and `Rc`

Open
#1,283 7 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

T-lang T-libs
Dominant language
Markdown
Stars
6.6k
Forks
1.7k
Avg merge
16h 14m
Merged PRs (30d)
1

Description

The idea occasionally comes up of whether Rc could take ownership of a Box and re-use the allocation, or conversely of converting a uniquely-owned Rc into a Box. While logically intuitive, this runs up against the physical limitation that Rc stores the reference counts inline in the allocation, ahead of the data, and so the two would not be compatible as-is. Making Rc store the reference counts out of line in a separate allocation (like std::shared_ptr) doesn't seem to be worth the overhead just to support this case.

If, however, we were to consider the ability to avoid some allocations in this way important enough, we do have a fairly straightforward option available to us to support it in some cases: publicly expose the RcBox type which comprises an Rc allocation (without necessarily providing access to the internal RcBox of any Rc - just the type). Something like this:

#[derive(Copy, Clone)]
pub struct RcBox<T: ?Sized> {
    strong: Cell<usize>, // private
    weak:   Cell<usize>, // private
    pub value: T
}

impl<T> RcBox<T> {
    pub fn new(value: T) -> RcBox<T> { ... }
}

impl<T: ?Sized> Rc<T> {
    pub fn from_box(source: Box<RcBox<T>>) -> Rc<T> { ... }
}

pub fn try_into_box<T: ?Sized>(self: Rc<T>) -> Result<Box<RcBox<T>>, Rc<T>> { ... }

(By keeping the reference count fields private, we can ensure that the reference count of any RcBox not currently inside of an Rc is always 1, so that from_box doesn't even need to check or reset them.)

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 by reviewing the proposed public RcBox type and the ownership and allocation-layout constraints described in the issue. Assess whether exposing RcBox, from_box, and try_into_box provides enough value to justify the API and safety implications; done requires a resolved design decision rather than a small isolated edit.

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
Stale
Clarity
Needs clarification
Newbie friendliness
25/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.