Lecture 22 - Owning collections: Vec, String, and capacity
Announcements
The three rules - do you remember them?
- Each value in Rust has an owner
- There can only be one owner at a time
- When the owner goes out of scope, the value will be dropped
Learning Objectives
By the end of today, you should be able to:
- Say what
pushdoes to a vector'slenandcap - List the four steps
pushtakes when the vector is full, and say why doubling keeps that rare - Explain why
names[0]can't move aStringout of aVec<String> - Make a
Box<T>and say when you might use it
We've been using Vec for weeks
We've been coding them, drawing them, and you're writing your own in Project 2 right now.
Today we get to two questions we've been able to dodge until now:
- What does a
Vecown, and what happens to that when you index into it? - What happens when it runs out of room?
Review: creating a Vec
fn main() { let numbers: Vec<i32> = Vec::new(); // empty, type from the annotation let scores = vec![85, 92, 78]; // with initial data let names: Vec<String> = Vec::new(); // empty, will hold Strings println!("{:?} {:?} {:?}", numbers, scores, names); }
scores in memory: 24-byte handle on the stack, the elements on the heap:
Stack: Heap:
┌─────────────────┐ ┌────┬────┬────┐
│ scores: Vec<i32>│ │ 85 │ 92 │ 78 │
│ ├ ptr ──────────┼─────▶│ │ │ │
│ ├ len: 3 │ └────┴────┴────┘
│ └ cap: 3 │
└─────────────────┘
Review: the basic operations
fn main() { let mut numbers = vec![1, 2, 3]; // Add elements (might reallocate!) numbers.push(4); numbers.push(5); println!("Vec: {:?}", numbers); // Other basic operations numbers.pop(); let num_len = numbers.len(); // Access elements (copies the value!) let first = numbers[0]; let third = numbers[2]; println!("First: {}, Third: {}, len {}", first, third, num_len); println!("Vec: {:?}", numbers); }
Capacity vs length
fn main() { let mut vec = Vec::with_capacity(4); // reserve room for 4, hold 0 println!("len {}, cap {}", vec.len(), vec.capacity()); vec.push(1); vec.push(2); println!("len {}, cap {}", vec.len(), vec.capacity()); vec.push(3); vec.push(4); println!("len {}, cap {}", vec.len(), vec.capacity()); vec.push(5); // no room. Now what? println!("len {}, cap {}", vec.len(), vec.capacity()); }
You've written this. Vec::with_capacity is your FastVec::with_capacity. The jump from 4 to 8 is Growth::Double.next_capacity(4), and the fifth push is your push.
What push does when the vector is full
Four steps (that all show up in Project 2):
- Ask the allocator for a bigger block:
next_capacity(4)= 8 - Copy every element from the old block into the new one
- Write the new element into the first free slot
- Free the old block
Before push(5):
Stack Heap
┌───────────┐ ┌───┬───┬───┬───┐
│ vec │ │ 1 │ 2 │ 3 │ 4 │
│ ├ ptr ────┼───▶│ │ │ │ │
│ ├ len: 4 │ └───┴───┴───┴───┘
│ └ cap: 4 │ full
└───────────┘
After push(5):
Stack Heap
┌───────────┐ ┌───┬───┬───┬───┐
│ vec │ │ x │ x │ x │ x │ freed
│ ├ ptr ──┐ │ └───┴───┴───┴───┘
│ ├ len: 5│ │ ┌───┬───┬───┬───┬───┬───┬───┬───┐
│ └ cap: 8│ │ │ 1 │ 2 │ 3 │ 4 │ 5 │ ? │ ? │ ? │
└─────────┼─┘ │ │ │ │ │ │ │ │ │
└─────▶└───┴───┴───┴───┴───┴───┴───┴───┘
The handle on the stack never moved. Its ptr and cap changed, and len went up by one, same as any push.
Why double, not add one? Doubling means most pushes find room and cost nothing; the copy happens rarely. Adding one would copy on every push. You'll explore the impact in Project 2!
Indexing copies the value out
fn main() { let numbers = vec![10, 20, 30, 40]; // These copy values from heap to stack: let first = numbers[0]; // first = 10 (copied) let second = numbers[1]; // second = 20 (copied) // Original Vec still owns the heap data: println!("Vec still works: {:?}", numbers); println!("Copied values: {}, {}", first, second); }
Stack: Heap:
┌─────────────────┐
│ main() │
│ ├ numbers: Vec │ ┌────┬────┬────┬────┐
│ │ ├ ptr ───────┼─────▶│ 10 │ 20 │ 30 │ 40 │
│ │ ├ len: 4 │ └────┴────┴────┴────┘
│ │ └ cap: 4 │
│ ├ first: 10 │
│ └ second: 20 │
└─────────────────┘
i32 is Copy, so numbers[0] copies the value from heap to stack. The vector still owns everything on the heap. Nothing moved.
Drawing practice: a Vec<String>
let names = vec![
String::from("Alice"),
String::from("Bob"),
];
Draw names in memory. Stack on the left, heap on the right, all types and metadata.
What about Vec<String>?
Heap data inside heap data. Each element is itself a handle, pointing at its own block of letters.
fn main() { let names = vec![ String::from("Alice"), String::from("Bob"), ]; // let first_name = names[0]; // does not compile. Why not? println!("{:?}", names); }
Think-pair-share: numbers[0] copied a 10 out. What would names[0] have to do?
Stack: Heap: More Heap:
┌───────────────────┐ ┌─────────────────┐ ┌─────┬─────┬─────┬─────┬─────┐
│ names: Vec<String>│ │ String "Alice" │ │ 'A' │ 'l' │ 'i' │ 'c' │ 'e' │
│ ├ ptr ────────────┼────▶│ ├ ptr ──────────┼───────▶┤ │ │ │ │ │
│ ├ len: 2 │ │ ├ len: 5 │ └─────┴─────┴─────┴─────┴─────┘
│ └ cap: 2 │ │ └ cap: 5 │
└───────────────────┘ ├─────────────────┤ ┌─────┬─────┬─────┐
│ String "Bob" │ │ 'B' │ 'o' │ 'b' │
│ ├ ptr ──────────┼───────▶┤ │ │ │
│ ├ len: 3 │ └─────┴─────┴─────┘
│ └ cap: 3 │
└─────────────────┘
String isn't Copy.
- Copying the handle would make two owners of the same letters, which breaks rule 2.
- Moving it out would leave a hole in the vector.
So anything that takes names[0] as a value, like let first = names[0]; or passing it to a function, is an error.
Looking at it in place is fine: names[0].len(), println!("{}", names[0]), and names[0].clone() all compile.
Box: a Vec of length one
You know what a Vec does. It puts values on the heap and keeps a small handle on the stack that points at them.
A Box<T> is the same idea for exactly one value. The handle is just the pointer: no len, no cap, because there's always one thing at the other end.
fn main() { let x = 42; // an i32 on the stack, as usual let b: Box<i32> = Box::new(42); // the same i32, on the heap, with a pointer to it println!("{} {}", x, b); } // b goes out of scope: the heap block is freed. Automatically.
Stack: Heap:
┌────────────────┐
│ main() │
│ ├ x: 42 │ ┌────┐
│ └ b: Box<i32> │ │ 42 │
│ └ ptr ──────┼──────▶│ │
└────────────────┘ └────┘
So a box puts anything on the heap, even a type that would normally sit on the stack, and gives you one pointer that owns it.
The box owns what it points at. Rule 3 does the rest: when the box is dropped, the value at the other end is freed with it. Same as a Vec, same as a String.
Why bother, for a 42? You wouldn't. We use Box when values are too big for the stack, or when the value has a size we can't know, like in trees later in the semester.
The same three rules apply for Box
fn main() { let b: Box<i32> = Box::new(42); println!("{}", b); drop(b); // destroys the box, which frees the 42 on the heap println!("{}", b); // the compiler knows b is gone }
Wednesday this was a String, and Monday it was C's use-after-free. C compiled it. Rust refuses, for a box the same as for anything else.
Box for data too big for the stack
Sometimes data that would usually go on the stack is just too big:
fn main() { let small_data = [0; 1000]; // 4 KB on the stack: fine let huge_data = [0; 10_000_000]; // 40 MB. The stack is 8 MB println!("{} and {} numbers", small_data.len(), huge_data.len()); }
Run it. The program never reaches the println!: the frame for main is too big to build.
The fix is to build it on the heap in the first place, and keep one small owner on the stack:
fn main() { let huge_data: Box<[i32]> = vec![0; 10_000_000].into_boxed_slice(); println!("Successfully created {} numbers", huge_data.len()); }
Box<[i32]> is a box owning ten million numbers. On the stack it's one pointer and one length.
When do you need a box?
- Large data: millions of records, big matrices
- Deep structures: nested data where the size isn't known up front
- Recursive types: lists and trees, which is Lecture 34
Boxes in boxes
You can put anything in a box, including things that already own heap data:
fn main() { // Box containing a Vec of Strings (heap in heap in heap!) let boxed_names = Box::new(vec![ String::from("Alice"), String::from("Bob"), ]); println!("Names in box: {:?}", boxed_names); // Box in a Box (why not?) let box_in_box = Box::new(Box::new(42)); println!("Deeply boxed value: {}", box_in_box); }
boxed_names: stack has aBoxpointer, heap has theVechandle, heap has theStringhandles, heap has the lettersbox_in_box: stack has aBoxpointer, heap has anotherBoxpointer, heap has the42
Activity 22, Part 1: the Box Office
Everything you need is now on the table: a Vec<String>, a push that runs out of room, a Box<Vec<String>>, and a box in a box.
See Activity 22. Cast to the front. Everyone else gets the sheet and the first question: which variables in main are still usable on the last two lines?
The same job, three prices
| Who decides when to free | When | What it costs you | |
|---|---|---|---|
| C | You | You write free | Seven kinds of bug |
| Python | Reference count, plus a collector for cycles | While the program runs | Time on every assignment, and pauses |
| Rust | The compiler, from the ownership rules | Before the program runs | Arguing with the borrow checker |
Rust moved the cost from run time to your time, which is a good trade-off if the program runs more often than you write it (like most programs!).
Take-aways
- A
Vec<T>is a stack handle (ptr, len, cap) pointing at heap elements. Same shape asString - Capacity isn't length. Growing past capacity allocates, copies, and frees, which shows up in Project 2's
push. Doubling keeps that rare. - Indexing a
Vec<i32>copies out a value. Indexing aVec<String>can't, because that would make two owners - A
Box<T>is like a Vec-of-one, or a pointer that owns what it points at - Boxes and vectors follow the same three rules as everything else
Activity 22, Part 2: three programs that won't compile
See Activity 22. Read the compiler message, say what went wrong in terms of owners, and write two fixes.