Rfcs: Way to create a Rc<[T]> from a Vec<T>

Created on 20 Apr 2017  ·  10Comments  ·  Source: rust-lang/rfcs

It should be possible to create an Rc<[T]> from a Vec<T>, but that is not possible right now without heavy use of transmute (which I'm sure some people are doing).

T-libs

Most helpful comment

@burdges An universal way to do that is #1138.

All 10 comments

See #1138

I hope people are not using transmute, because you can't safely transmute one to the other without resizing the allocation to make room for the reference counts.

We can already convert Vec<T> to Box<[T]>, so this would be easily solved with https://github.com/rust-lang/rust/issues/29953

Although I'm curious, why would anyone use unsafe code, or even transmute, instead of just using Rc<Vec<T>>? This is not a rhetorical question.

This comment would also be relevant: https://github.com/rust-lang/rust/issues/29953#issuecomment-158432454

Vec<T>←→ Box<[T]> works because the allocated memory is of the same size, with Rc<T> its different, and would require re-allocation and most likely also copying (some system allocators allow you to try to change the size of your allocation), which would make this non-O(1).

You could create new RcVec<T> and ArcVec<T> types with zero reallocation conversions to/from Box<Rc<[T]>> and Box<Arc<[T]>>.

@burdges An universal way to do that is #1138.

I suspect the usual use case would be that the code would build the array in Vec<T> and then convert it to Rc<[T]> for the consumer. Building it would be O(n) regardless, and the memcpy will likely matter much less than the work expended on creating it. As long as it's documented as such, I don't see a problem with it.

Does any code actually do this conversion at the moment? Even if allocator magic as proposed by @eddyb is accepted, it will take a lot of time to land, but experiments like RcVec<T> can be realized right this afternoon as a 3rd party crate.

Was this page helpful?
0 / 5 - 0 ratings