If you are inclined to use Vec directly, then @ user4815162342 explained why what you are asking for is not possible.
However, if (1) you really need efficient removal from the front and (2) the adjacency value, so that VecDeque not suitable, then you can also create your own container. I once had those (two) strict requirements in C ++, and C ++ in this case is much more dangerous than Rust.
The basic structure:
struct DVec<T> { data: *mut T, length: usize, offset: usize, capacity: usize, _marker: PhantomData<T>, }
Depending on your requirements, you can reduce the size down by using u32 instead of usize (which still allows you to use 4 billion elements!).
After that, DVec::drain(..n) and DVec::drain(0..n) are implemented by bumping offset by n .
This data structure offers an interface similar to VecDeque , with the following changes:
- data is stored contiguously, so it implements
Deref<Target = [T]> , - The element insert at both ends is amortized O (1),
- removing an element from either end is O (1).
In C ++, it hurts to write because not all objects are movable, and moving can throw an exception; in Rust, all objects are movable, and moving is an exception, so it is much simpler.
source share