Lecture 33 - Queues: VecDeque and the ring buffer
Announcements
Learning objectives
By the end of today, you should be able to:
- Explain why popping the front of a
Vecis slow, and what a ring buffer does about it - Trace
push_backandpop_fronton a ring, including the wrap, and say where each element lives - Use
VecDequeas a queue - Choose between
Vec,VecDeque, andBinaryHeapfor a problem, and say why
Pop the oldest
Monday's table had a hole in it:
| Need | Use |
|---|---|
| Pop the newest first | Vec |
| Pop the oldest first | ? |
| Pop by priority | BinaryHeap |
Vec is slow at the front, and VecDeque is going to fix that.
Two different "stacks"
Monday we saw "heap" had two very different definitions. Today we do the same for "stack":
Stack memory:
- Where local variables live, one frame per function call
- The last function called is the first to return
Stack data structure, a way of keeping things:
pushon top,popoff the top,peekat the top- The last thing in is the first thing out
Same word because they behave the same way. The frames do form a stack. One is a region of memory, the other is a rule for a collection.
Vec is already a stack
fn main() { let mut stack: Vec<i32> = Vec::new(); stack.push(10); stack.push(20); stack.push(30); println!("{:?}", stack); // [10, 20, 30] println!("{:?}", stack.pop()); // Some(30) println!("{:?}", stack.last()); // Some(20), still there println!("{:?}", stack); // [10, 20] }
push and pop work on the end, and the end is where a Vec is cheap (because you don't need to slide anything else around).
Nothing new today on Vec.
A queue: first in, first out
A stack is LIFO (last in, first out)
A queue is FIFO (first in, first out)
Real world queues: lines at the store, printing at a shared printer, a set of downloads in the order you clicked them.
- Join at the back
- Served from the front
- The first one in is the first one out

A stack has one "editable" end. A queue has both ends: things go in at one and come out at the other.
Vec as a queue
Joining at the back is push, and that's cheap. Serving from the front:
let mut line = vec![1, 2, 3, 4, 5];
let served = line.remove(0); // 1
println!("{:?}", line); // [2, 3, 4, 5]
remove(0) gives the right answer. What does it cost?
Let's time it
100,000 jobs through a queue, one at a time:
use std::collections::VecDeque; use std::time::Instant; fn main() { let n: u64 = 100_000; let mut line: Vec<u64> = (0..n).collect(); let mut served = 0; let start = Instant::now(); while !line.is_empty() { served += line.remove(0); } println!("Vec::remove(0), {} times: {:?}", n, start.elapsed()); let mut line: VecDeque<u64> = (0..n).collect(); let start = Instant::now(); while !line.is_empty() { served += line.pop_front().unwrap(); } println!("VecDeque::pop_front, {} times: {:?}", n, start.elapsed()); println!("checksum {}", served); // so the compiler can't skip the loops }
VecDeque: a Vec with a front door
"Deque" is short for double-ended queue. We pronounce VecDeque "vec-deck."
use std::collections::VecDeque; fn main() { let mut line: VecDeque<i32> = VecDeque::new(); line.push_back(10); // join at the back line.push_back(20); line.push_back(30); println!("{:?}", line); // [10, 20, 30] println!("{:?}", line.pop_front()); // Some(10), served println!("{:?}", line.front()); // Some(20), next up line.push_front(5); // cut the line println!("{:?}", line); // [5, 20, 30] println!("{:?}", line.pop_back()); // Some(30) }
Four operations, both ends, all O(1).
How: a ring
One block, capacity 4. A head marks the front, len counts what's in it.
push_back(10), push_back(20), push_back(30)
slot: 0 1 2 3
┌─────┬─────┬─────┬─────┐
│ 10 │ 20 │ 30 │ │ head: 0 len: 3
└─────┴─────┴─────┴─────┘
▲
head
pop_front() -> Some(10)
┌─────┬─────┬─────┬─────┐
│ │ 20 │ 30 │ │ head: 1 len: 2
└─────┴─────┴─────┴─────┘
▲
head
push_back(40)
┌─────┬─────┬─────┬─────┐
│ │ 20 │ 30 │ 40 │ head: 1 len: 3
└─────┴─────┴─────┴─────┘
▲
head
push_back(50) wraps around
┌─────┬─────┬─────┬─────┐
│ 50 │ 20 │ 30 │ 40 │ head: 1 len: 4
└─────┴─────┴─────┴─────┘
▲
head
Nothing moved. The front moved, and the back wrapped around to slot 0. The block is a ring: walk off the right end and you're back at the left.
println!("{:?}", line) prints [20, 30, 40, 50], front to back, because it starts at head and walks the ring.
Activity 33, Problem 1: trace a ring
See Problem 1 on Activity 33.
Answer.
push_back x4: [ 7 | 3 | 9 | 10 ] head 0 len 4
pop_front x2: [ | | 9 | 10 ] head 2 len 2
push_back(4): [ 4 | | 9 | 10 ] head 2 len 3
push_front(8): [ 4 | 8 | 9 | 10 ] head 1 len 4
[8, 9, 10, 4], fromheadaround the ring- The front is slot 1 (the 8), because
push_frontsteppedheadback from 2 to 1. The back is slot 0 (the 4), because it wrapped
Where it lives: your Vec with one more piece of metadata
let mut line = VecDeque::with_capacity(4);
// push_back 10, 20, 30, pop_front, push_back 40, push_back 50
Stack: Heap:
┌───────────────────────────┐ ┌────┬────┬────┬────┐
│ main() │ │ 50 │ 20 │ 30 │ 40 │
│ └ line: VecDeque<i32> │ └────┴────┴────┴────┘
│ ├ ptr ─────────────────┼───▶ 0 1 2 3
│ ├ cap: 4 │
│ ├ head: 1 │
│ └ len: 4 │
└───────────────────────────┘
In Project 2 you built FastVec with ptr, len, and cap. This is that struct with one more field. Every operation is arithmetic on head:
- Element
iof the queue is at slot(head + i) % cap pop_front:head = (head + 1) % cap,len -= 1push_back: write at(head + len) % cap,len += 1
Comparing what we've seen so far:
- Hash maps used
hash % 8to find the index - Max heaps used
(i - 1) / 2 - Now we have
(head + len) % cap
What they have in common: one block in memory, and arithmetic to decide where things go.
The ring, for real
Rust won't show us head directly, but as_slices hands back the two pieces, and the first piece starts at head. Subtract the block's base pointer, and we can draw every slot:
use std::collections::VecDeque; // Print the block the way it sits in memory: every slot, in slot order, plus head fn show_raw(line: &VecDeque<i32>, base: *const i32) { let (first, second) = line.as_slices(); let head = (first.as_ptr() as usize - base as usize) / 4; // 4 bytes per i32 let mut slots: Vec<String> = vec!["__".to_string(); line.capacity()]; for (i, x) in first.iter().enumerate() { slots[head + i] = x.to_string(); } for (i, x) in second.iter().enumerate() { slots[i] = x.to_string(); } println!("[{}] head {} len {}", slots.join(" | "), head, line.len()); } fn main() { let mut line: VecDeque<i32> = VecDeque::with_capacity(4); let base = line.as_slices().0.as_ptr(); // slot 0, before anything moves line.push_back(10); line.push_back(20); line.push_back(30); show_raw(&line, base); line.pop_front(); show_raw(&line, base); line.push_back(40); show_raw(&line, base); line.push_back(50); show_raw(&line, base); println!("{:?}", line); // what Debug printing shows line.push_back(60); let base = line.as_slices().0.as_ptr(); // a new block after the doubling show_raw(&line, base); }
We had to do all this because {:?} starts at head and walks the ring, so it shows the queue in order and hides the wrap.
When it fills up
The ring was full at four. push_back(60) does what Vec does: double the block, copy everything across, free the old one. One extra step: the copy un-wraps the ring, so the queue is in one piece again and head is back at 0.
[50 | 20 | 30 | 40] head 1 len 4 cap 4, wrapped
[20 | 30 | 40 | 50 | 60 | __ | __ | __] head 0 len 5 cap 8, one piece
That's why base had to be captured again: the old block was freed, and the queue lives somewhere new.
So why not always VecDeque?
There are three costs:
- Every index is arithmetic.
v[i]is pointer plus offset.line[i]is pointer plus(head + i) % cap - The data can be in two pieces. No slice across the wrap, so no
sort()and no&line[1..3]untilmake_contiguous()copies it straight - It's the less simple thing. When you never touch the front,
Vecis smaller, simpler, and a little faster
Use VecDeque when you touch the front. Otherwise Vec.
Both ends: the last five readings
A sensor reports every second. You want the average of the last five readings, always.
use std::collections::VecDeque; fn main() { let readings = [71, 73, 70, 75, 78, 80, 77, 79]; let mut window: VecDeque<i32> = VecDeque::new(); for r in readings { window.push_back(r); // newest in at the back if window.len() > 5 { window.pop_front(); // oldest out at the front } let total: i32 = window.iter().sum(); println!("{:?} average {:.1}", window, total as f64 / window.len() as f64); } }
The window slides along the stream. Each step is one push_back and one pop_front, O(1) each, whatever the stream's length. A Vec would shift four readings every second.
We saw .iter().sum() briefly in the strings and slices lecture. After Thanksgiving we'll see what else .iter() can do.
Think-pair-share: which structure?
Vec, VecDeque, or Monday's BinaryHeap?
- The browser's back button
- A download queue: files download in the order you clicked
- Undo and redo
- A recent-files list: most recent first, never more than ten
Answer.
Vec, as a stack. Back ispopVecDeque. First clicked, first downloaded:push_back,pop_front- Two
Vecs. Undo pops the undo stack and pushes the redo stack. A new action clears redo VecDeque.push_frontthe newest, and whenlenpasses ten,pop_backthe oldest. Both ends in one structure
Summary of this week's structures
| Need | Use | Under the hood |
|---|---|---|
| Pop the newest | Vec | One block |
| Pop the oldest | VecDeque | One block, a head, % cap |
| Pop the biggest | BinaryHeap | One block, (i - 1) / 2 |
| Is this here? | HashSet | One block of buckets, hash % buckets |
| Look it up by key | HashMap | The same, with a value next to each key |
Every one of them is a Vec-shaped block on the heap plus some arithmetic. (Friday we'll see something with a different shape.)
Activity 33
See Activity 33. Problem 1 is done, so start at Problem 2.
Appendix: LinkedList
There's a third way to keep a line: each element holds a pointer to the next one, and they can sit anywhere in memory. Rust has std::collections::LinkedList, and almost nobody uses it. It makes it easy to insert between two items, but every element needs its own allocation of memory, and there's no index, so doing something like finding the tenth element means following nine pointers.
On Friday we'll build one by hand anyway, because it's the simplest structure that isn't one block, and it's our way into trees.
Appendix: make_contiguous
If you need the queue as one slice, for sort or a range, make_contiguous() copies the ring straight and hands back a &mut [T].