Why does calling `sort()` on a Rust VecDeque fail to compile, and what do `as_slices` and `make_contiguous` give you instead?
answer
- ring buffer wraps around
- two runs, not one
- no Deref to a slice
- rotate in place, no allocation
basics
~20 sA VecDeque's elements can wrap past the end of its buffer, so it cannot deref to one slice and has no sort method (E0599). as_slices returns the two halves; make_contiguous rearranges them in place into one &mut [T].
solid answer
~40 s`VecDeque` is a ring buffer, so its elements may sit in two runs: from `head` to the end of the allocation, then from slot 0. A slice must be contiguous, so `VecDeque` does not implement `Deref<Target = [T]>`, and slice methods such as `sort` are missing: `buf.sort()` fails with E0599, and passing `&buf` where `&[T]` is expected fails with E0308. `as_slices()` returns `(&[T], &[T])`, the two runs in logical order, without moving anything. `make_contiguous()` rearranges the storage in place without allocating, keeps the order, and returns `&mut [T]`, so `buf.make_contiguous().sort()` is the idiom. It moves elements when the deque wraps, so its cost grows with the length.
code
rust · 24 linesuse std::collections::VecDeque;
fn checksum(bytes: &[u8]) -> u32 {
bytes.iter().map(|&b| u32::from(b)).sum()
}
fn main() {
let mut buf: VecDeque<u8> = VecDeque::with_capacity(4);
buf.extend([1, 2, 3, 4]);
buf.pop_front();
buf.pop_front();
buf.push_back(5);
buf.push_back(6); // wraps around the end of the allocation
let (front, back) = buf.as_slices();
println!("as_slices: {front:?} + {back:?}");
// checksum(&buf); // E0308: expected `&[u8]`, found `&VecDeque<u8>`
let whole: &mut [u8] = buf.make_contiguous();
whole.sort_unstable_by(|a, b| b.cmp(a));
println!("contiguous and sorted: {whole:?}");
println!("checksum = {}", checksum(buf.as_slices().0));
println!("as_slices now: {:?}", buf.as_slices());
}go deeper
Recall that VecDeque is not a slice and lacks slice methods like sort; make_contiguous is the way to get one.
Explain the two runs of a wrapped ring buffer and what as_slices returns, including the empty second slice when nothing wraps.
State make_contiguous's contract — no allocation, order preserved, moves only when wrapped — and the Vec conversion costs, then pick as_slices for hot paths.
In APIs that take a queue, accept the two-slice view where possible so callers are not forced to rearrange their buffers on every call.
## Why there is no single slice `VecDeque<T>` is a **ring buffer**: one allocation, a `head` index where the logical first element sits, and a length. Pushing at the back writes past the last element; when that reaches the end of the allocation it **wraps** to slot 0. Pushing at the front writes just before `head`, wrapping backwards. So the elements are always in two runs at most, but those runs are not necessarily adjacent in memory. A slice `&[T]` is a pointer plus a length over **contiguous** memory. A wrapped deque cannot be described by one, which is why `VecDeque` does **not** implement `Deref<Target = [T]>` the way `Vec` does. Every slice method `Vec` borrows through deref — `sort`, `chunks`, `windows`, `contains` — is therefore absent unless `VecDeque` defines its own, and code that expects a slice fails to compile: - `buf.sort()` fails with **E0599**: "no method named `sort` found for struct `VecDeque<T, A>` in the current scope". - `checksum(&buf)` where `checksum` takes `&[u8]` fails with **E0308**: "expected `&[u8]`, found `&VecDeque<u8>`". - `&buf[0..2]` fails with **E0308** too, because `VecDeque` implements `Index<usize>` only. `VecDeque` does provide many methods of its own — `iter`, `contains`, `range`, `binary_search`, `retain`, `rotate_left` — so check its API before reaching for a slice. ## `as_slices` and `as_mut_slices` `as_slices(&self) -> (&[T], &[T])` returns the two runs **in logical order**: the first slice holds the front of the deque, the second the rest. If the deque does not wrap, the second slice is empty. `as_mut_slices` is the mutable twin. These are free: no element moves. They suit any job that can process two pieces in sequence, such as writing both halves to a socket, hashing them in order, or summing them. They do not suit an algorithm that needs one view of everything, such as sorting. ## `make_contiguous` `make_contiguous(&mut self) -> &mut [T]` **rearranges the storage in place** so the elements form one run, then returns that run as a mutable slice. std documents three properties: 1. It **does not allocate**. 2. It **does not change the logical order** of the elements. 3. Afterwards, `as_slices` and `as_mut_slices` return the entire contents in the first slice. It is not free, though: when the deque is wrapped, elements are moved, so the cost grows with the length. The idiom for sorting a deque is `buf.make_contiguous().sort()`, straight from std's docs. To get a shared slice afterwards while keeping `buf` usable, call `make_contiguous()` and then read `buf.as_slices().0`. ## Converting to and from `Vec` | Conversion | Allocation | Element movement | |---|---|---| | `VecDeque::from(vec)` | none | none; guaranteed O(1) | | `Vec::from(deque)` | none | O(n) moves if the run is not at the start of the allocation | | `buf.make_contiguous()` | none | moves only when the deque wraps | | `buf.iter().copied().collect::<Vec<_>>()` | a new buffer | copies every element | The documented O(1) `Vec -> VecDeque` guarantee is useful when you build a batch in a `Vec` and then serve it as a queue. ## When this matters - **Sorting or binary-searching by a custom key**: call `make_contiguous` once, then use slice methods on the result. - **Hot loops over two halves**: iterate `as_slices` rather than forcing contiguity on every pass. - **Handing data to a slice API**: `make_contiguous` then `as_slices().0` avoids allocating a copy. - **Repeated calls**: once contiguous, a second `make_contiguous` is cheap until pushes wrap the buffer again. ## A worked trace Take a deque whose buffer holds exactly four bytes, which is what `with_capacity(4)` gave in the example run. Push 1, 2, 3, 4: the run fills slots 0 to 3 and `head` is 0. Pop the front twice: `head` moves to slot 2, and slots 0 and 1 are free. Push 5 and 6: there is no room after slot 3, so they wrap into slots 0 and 1. Now the logical order is 3, 4, 5, 6, but memory holds 5, 6, 3, 4. `as_slices` reports `[3, 4]` and `[5, 6]`. After `make_contiguous`, memory holds the elements in logical order as one run and the second slice is empty. Sorting the returned `&mut [u8]` in descending order then gives `[6, 5, 4, 3]` — exactly the program in the code example.
- What does converting a VecDeque into a Vec cost?`Vec::from(deque)` never reallocates; it reuses the deque's buffer. If the elements do not start at the beginning of the allocation, it moves them into place, which is O(n). The other direction, `VecDeque::from(vec)`, is guaranteed O(1) with no allocation and no moves, because the Vec's buffer is reused as-is, with the deque's head at slot 0.
- How do you get a shared &[T] of the whole deque while still being able to read the deque itself?Call `buf.make_contiguous();` as a statement so its `&mut` borrow ends, then take `let (all, rest) = buf.as_slices();`. After `make_contiguous`, `rest` is empty and `all` covers every element. Holding the `&mut [T]` that `make_contiguous` returned would block other reads until it is last used.
- VecDeque derefs to a slice just like Vec does.
- as_slices returns one slice when the deque is sorted.
- make_contiguous allocates a fresh buffer and copies elements.
- make_contiguous is free, so call it before every read.
- VecDeque supports range indexing like &buf[1..3].