Add O(1) Vec -> VecDeque conversion guarantee by Sp00ph · Pull Request #105128 · rust-lang/rust (original) (raw)

@rust-lang/libs-api:
@rfcbot fcp merge

Can we guarantee that converting Vec to VecDeque (using From) is able to keep the original allocation, not dropping unused capacity or needing to snap to a particular element count, such as power-of-2?

rust-lang/libs-team#138 has the justifications. Here is what I found compelling:

By guaranteeing that this conversion be O(1), it allows users to freely convert between Vec<T> and VecDeque<T> without ever reallocating and makes it trivial to e.g. turn an existing Vec<T> into a FIFO queue.

As a bonus if the O(1) conversion happens, we could delegate VecDeque: FromIterator to Vec: FromIterator, getting a bunch of optimization for free (by not needing to reimplement them on VecDeque) and potentially saving a bunch of monomorphization work too (since collecting an iterator into either container type can reuse the same code).

(Could even spell it impl<I, T> FromIterator<I> for VecDeque<T> where Vec<T>: FromIterator<I> and never again worry about keeping them in sync.)

I'd love to have this. It'd be amazing to change the answer for "how do I remove a bunch of things from the front of a Vec?" to change from "well, let me tell you about a bunch options with into_iter and drain and ..." to "It's O(1) to convert it to a VecDeque, so just do that -- you can always convert it back again for just the unavoidable data movement cost anyway if you still need a Vec".

Be aware of the tradeoff that this complicates ever adopting a more sophisticated platform-specific deque internals, such as seen in https://crates.io/crates/slice-deque.