Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Lecture 31 - Hashing: HashMap, HashSet

A row of cells beside a set of keys mapped to buckets

Announcements




Learning objectives

By the end of today, you should be able to:

  • Use HashSet<T> to check membership and find unique values
  • Explain what a hash function does, and how a key becomes a bucket index
  • Read HashMap<K, V> code that inserts, looks up, counts, and iterates
  • Explain how a site checks a password without ever storing it, and what a weak hash costs
  • Say what insert, get, and contains cost, and why they beat searching a Vec
  • Draw a HashMap on the stack and the heap

That username is taken

You pick a username on a site with a billion accounts. The moment you finish typing, it tells you the name is taken.

How did it check them all that fast?

Lay out the cards

Imagine this: I hand you 1,000 index cards, each with a name on it (first and last). In a minute I'll call out a name, and the faster you can find the card the more money I'll give you.

You have a table and five minutes to get ready. How do you lay them out?

Think/pair/share

The solution: hashes

A hash function takes any input and turns it into a number.

  • Deterministic: the same input always gives the same number
  • Fast: a few nanoseconds for a short string
  • Uniform: spreads inputs evenly across the range
  • Avalanche: a tiny change in the input changes the whole output
    • hash("Alice") = 63350368
    • hash("alice") = 92903040
  • Hard to invert, for the good ones: given the number, you can't recover the input. (Question - why would this matter?)

A toy hash function

A simplified one, to show the idea. Real ones are much more careful.

fn toy_hash(s: &str) -> u64 {
    let mut hash: u64 = 0;
    for ch in s.chars() {
        hash = hash.wrapping_mul(31).wrapping_add(ch as u64);
    }
    hash
}

fn main() {
    println!("{}", toy_hash("Alice"));  
    println!("{}", toy_hash("Bob"));   
    // println!("{}", toy_hash("alice"));  
}

Multiply, add, multiply, add. Every character shifts everything that came before it, which is where the avalanche comes from.

What does Rust use? By default, SipHash 1-3. Slower than the toy, and built so that nobody can feed your program keys chosen to collide on purpose. Have fun going down that rabbit hole.

So what do we do with the hash?

Every key is now a number, and the numbers are spread evenly. Can we use the number as the shelf?

hash("Alice") = 63350368, so Alice goes on shelf 63,350,368. A u64 goes up to about , so that's shelves for 1,000 cards, and nearly all of them empty.

So we pick how many shelves we can afford, say 8, and fold every hash onto them with modulo:

hash("Alice") % 8  =  63350368 % 8  =  0
hash("Bob")   % 8  =     66965 % 8  =  5
  [0]     [1]     [2]     [3]     [4]     [5]     [6]     [7]
 Alice                                    Bob

Each shelf is a bucket, and the number the modulo gives is its bucket index. The hashes are spread evenly, so the buckets fill evenly too: no 20-deep A pile, and no empty Q pile.

A lookup is three steps

That's the whole machine: a hash function, plus one array of buckets on the heap. To find a key:

  1. Hash the key
  2. Modulo to get a bucket index
  3. Go straight to that bucket and compare the key

Three steps. The number of steps doesn't depend on how many keys are stored. A billion or ten, same three steps.

We'll draw the array in full once there are values in it. First, let's build one.

Activity 31, Round 1: everyone to your bucket

The room is the hash table. Eight buckets on the walls, 0 to 7. Your key is your first name.

hash(name) = value of the first letter, A is 1 through Z is 26. Bucket = hash % 8.

BucketFirst letter
0H P X
1A I Q Y
2B J R Z
3C K S
4D L T
5E M U
6F N V
7G O W

Go. Then write your bucket, the longest pile, and the empty buckets on your sheet.

When two keys land in the same bucket

With 8 buckets and 9 keys, two of them share a bucket. That's a collision, and it happens all the time.

The fix is simple: if the bucket's taken by a different key, look in the next one. Keep going until you find the key or hit an empty bucket.

hash("Alice") % 8 = 0        bucket [0]: Alice      found
hash("Erin")  % 8 = 0        bucket [0]: Alice      taken by Alice
                             bucket [1]: Erin       found
hash("Zed")   % 8 = 0        bucket [0]: Alice      no
                             bucket [1]: Erin       no
                             bucket [2]: empty      stop: Zed isn't here

Collisions cost extra comparisons. Too many and the table slows to a crawl, so it grows before it fills up: at about 7/8 full it doubles the bucket array and re-places every key.

That's why there's always an empty bucket to stop a search at.

Let's watch it grow

use std::collections::HashSet;

// std doesn't report the bucket count, but it's always the next power
// of two that keeps the table at most 7/8 full
fn buckets(cap: usize) -> usize {
    if cap == 0 { 0 }
    else if cap < 4 { 4 }
    else if cap < 8 { 8 }
    else { (cap * 8 / 7).next_power_of_two() }
}

fn main() {
    let mut seen: HashSet<i32> = HashSet::new();
    println!("len {:>2}, cap {:>2}, buckets {:>2}",
             seen.len(), seen.capacity(), buckets(seen.capacity()));

    for i in 1..=15 {
        seen.insert(i);
        println!("len {:>2}, cap {:>2}, buckets {:>2}",
                 seen.len(), seen.capacity(), buckets(seen.capacity()));
    }
}

We drew this for Vec a few weeks ago: when push runs out of room, it doubles, copies everything across, and frees the old block. The hash table does the same, with one extra step: every key gets re-hashed, because % 8 just became % 16.

The thing we just built is a HashSet

A bucket array, a hash function, and your keys in the buckets. In Rust that's HashSet<T>: a collection of unique values, on the heap, that answers "is this in here?"

(Yep, it's a Python set.)

use std::collections::HashSet;

fn main() {
    let mut taken = HashSet::new();
    taken.insert("alice_smith".to_string());
    taken.insert("bob_j".to_string());
    taken.insert("carol_w".to_string());

    // The username check. No loop.
    if taken.contains("rustacean_99") {
        println!("taken");
    } else {
        println!("available");
    }
}

.contains() is hash, modulo, compare. Three steps whether the set holds three names or a billion.

What can be a T?

The compiler has to hash the key and compare it to the one in the bucket. So the type has to promise it can do both:

use std::collections::HashSet;

#[derive(Debug)]
struct Striker { goals: u32, name: String }

fn main() {
    let mut squad = HashSet::new();
    squad.insert(Striker { goals: 27, name: String::from("Haaland") });
    println!("{:?}", squad);
}
error[E0277]: the trait bound `Striker: Eq` is not satisfied
note: required by a bound in `HashSet::<T, S, A>::insert`
    |     T: Eq + Hash,

That's a trait bound, written by the standard library: insert works for any T with Eq and Hash. Both are traits you can derive, the same way we derived traits on Monday:

#[derive(Debug, PartialEq, Eq, Hash)]
struct Striker { goals: u32, name: String }

Numbers, char, String, and &str all have them already. Every key in a HashMap needs them too.

Pour a Vec in, and the duplicates vanish

You have a customer list, and some customers appear more than once:

use std::collections::HashSet;

fn main() {
    let customers = vec!["Alice", "Bob", "Alice", "Carol", "Bob", "David", "Alice"];

    // Pour the Vec into a HashSet. Duplicates vanish on the way in.
    let unique_customers: HashSet<&str> = customers.iter().cloned().collect();

    println!("Original list: {} customers", customers.len());   // 7
    println!("Unique customers: {}", unique_customers.len());   // 4

    for customer in &unique_customers {
        println!("Customer: {}", customer);
    }
}

.collect() builds whatever collection the type annotation asks for. Here that's a HashSet<&str>, so inserting a name that's already there does nothing.

.iter().cloned() copies each item in and leaves the Vec alone. .into_iter() would move the items in instead, and the Vec would be gone. The appendix has the two side by side.

What each one costs

Most operations are cheap, and once in a while one is expensive. The word for "expensive rarely, free the rest of the time, cheap on average" is amortized.

A Vec with n elements:

OperationCostWhy
vec[i]O(1)Pointer plus offset
vec.push(x)O(1) amortizedUsually one write. Every doubling, a copy of n
vec.pop()O(1)Decrement len
vec.insert(0, x)O(n)Shift everything right
vec.contains(&x)O(n)Look at every element until found

A HashSet with n keys:

OperationCostWhy
set.contains(&x)O(1) averageHash, modulo, compare. A few extra on a collision
set.insert(x)O(1) amortizedSame, plus the occasional doubling and re-hash
set.remove(&x)O(1) averageSame

The one Vec can't do in O(1) is the one HashSet is for: asking is this thing here?

So which is faster?

You run a game with 100,000 registered player IDs. 10,000 match results come in, and you need to know which ones belong to registered players.

// Option A: the IDs in a Vec
let players_vec = vec![/* 100,000 player IDs */];
for result in results.iter() {
    if players_vec.contains(&result.player_id) {
        // count it
    }
}
// Option B: the IDs in a HashSet
let players_set: HashSet<_> = player_ids.into_iter().collect();
for result in results.iter() {
    if players_set.contains(&result.player_id) {
        // count it
    }
}

Which is faster? How much faster?

They look the same. The difference is what contains does:

  • Vec::contains may look at all 100,000 IDs for each result. 100,000 times 10,000 = a billion comparisons
  • HashSet::contains hashes the ID and checks one bucket. 10,000 lookups

Now staple a value to each card

Back at the table of names, imagine writing a phone number on every name card.

Same piles, but now the question is what a person's phone number is.

That's a HashMap<K, V>: the same bucket array, with a value stored next to each key.

(Yep, it's a Python dict.)

use std::collections::HashMap;

fn main() {
    // A phone book, from name to number
    let mut customer_data = HashMap::new();
    customer_data.insert("Alice Smith".to_string(), 12345);
    customer_data.insert("Bob Jones".to_string(), 56789);
    customer_data.insert("Carol White".to_string(), 11235);

    // Look Alice up. No loop.
    match customer_data.get("Alice Smith") {
        Some(number) => println!("Alice's number is {}", number),
        None => println!("Alice not found"),
    }
}

.get() returns an Option, because the key might not be there. Same three steps as the set, so the same costs: get, insert, and contains_key are all O(1) average.

customer_data["Alice Smith"] also works, but it panics if the key is missing. Use .get() unless you're certain.

Memory layout: the whole picture

let mut customer_data = HashMap::new();
customer_data.insert("Alice Smith".to_string(), 12345);
customer_data.insert("Bob Jones".to_string(), 56789);
Stack:                        Heap: the bucket array            More heap: the keys
┌────────────────────────┐    ┌───┬────────────────────────┐
│ main()                 │    │ 0 │ empty                  │
│ └ customer_data:       │    ├───┼────────────────────────┤
│    HashMap<String,i32> │    │ 1 │ key: String            │    ┌───┬───┬───┬───┬───┬───┬───┬───┬───┐
│    ├ ptr ──────────────┼───▶│   │  ├ ptr ────────────────┼───▶│ B │ o │ b │   │ J │ o │ n │ e │ s │
│    ├ len: 2            │    │   │  ├ len: 9              │    └───┴───┴───┴───┴───┴───┴───┴───┴───┘
│    └ cap: 3            │    │   │  └ cap: 9              │
└────────────────────────┘    │   │ value: i32 = 56789     │
                              ├───┼────────────────────────┤
                              │ 2 │ empty                  │
                              ├───┼────────────────────────┤
                              │ 3 │ key: String            │    ┌───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┐
                              │   │  ├ ptr ────────────────┼───▶│ A │ l │ i │ c │ e │   │ S │ m │ i │ t │ h │
                              │   │  ├ len: 11             │    └───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┘
                              │   │  └ cap: 11             │
                              │   │ value: i32 = 12345     │
                              └───┴────────────────────────┘
Stack:                     Heap: the bucket array         More heap: the keys
┌─────────────────────┐    ┌───┬─────────────────────┐
│ main()              │    │ 0 │ empty               │
│ └ customer_data:    │    ├───┼─────────────────────┤
│    HashMap<String,  │    │ 1 │ key: String         │
│            i32>     │    │   │  ├ ptr ─────────────┼───▶ "Bob Jones"
│    ├ ptr ───────────┼───▶│   │  ├ len: 9           │
│    ├ len: 2         │    │   │  └ cap: 9           │
│    └ cap: 3         │    │   │ value: i32 = 56789  │
└─────────────────────┘    ├───┼─────────────────────┤
                           │ 2 │ empty               │
                           ├───┼─────────────────────┤
                           │ 3 │ key: String         │
                           │   │  ├ ptr ─────────────┼───▶ "Alice Smith"
                           │   │  ├ len: 11          │
                           │   │  └ cap: 11          │
                           │   │ value: i32 = 12345  │
                           └───┴─────────────────────┘
  • The handle on the stack is the same shape as Vec's: a pointer, a length, a capacity
  • The bucket array is on the heap. Each bucket holds one key and one value, or is empty
  • The keys are Strings, so each one is a handle pointing at its own letters, further out on the heap
  • Which bucket a pair lands in is the hash of its key, modulo the bucket count
  • Four buckets and cap: 3: it grows before it's full, so there's always an empty bucket to stop a search at
  • A HashSet is this picture without the value rows

HashMap: the methods you'll read

Be able to read these. You don't have to write them from memory.

use std::collections::HashMap;

fn main() {
    let mut prices: HashMap<String, f64> = HashMap::new();

    prices.insert("bat".to_string(), 30.0);  // add, or overwrite if the key's there
    prices.insert("glove".to_string(), 45.0);
    println!("{:?}", prices.get("bat"));    // Some(30.0), or None if it's missing
    println!("{}", prices.contains_key("helmet")); // false
    prices.remove("glove");                    // takes the pair out

    for (item, price) in &prices {           // references, in random order
        println!("{item}: {price}");
    }

    // Counting: find the slot, put 0 there if it's empty, add 1 through the &mut
    let mut counts: HashMap<&str, u32> = HashMap::new();
    for word in "the cat sat on the mat".split_whitespace() {
        *counts.entry(word).or_insert(0) += 1;
    }
    println!("{:?}", counts);
}

The order is random, and changes from one run to the next. It's whatever order the buckets happen to be in. Never write a test that depends on the order of a hashmap or hashset (or a Python dict or set). If you need an order, collect the keys into a Vec and sort.

Think-pair-share: what happens here?

use std::collections::HashMap;

fn main() {
    let product = String::from("smartphone");
    let mut prices = HashMap::new();
    prices.insert(product, 599.99);
    println!("Product: {}", product);
}

Answer. It doesn't compile: "borrow of moved value: product".

insert takes its arguments in, so the String moved into the hashmap. If we need product afterwards, insert product.clone().

Storing passwords

A site has to check your password every time you log in. It must never store the password.

How would you use a hash function for this?

  1. When you sign up, the site stores hash(password), a number
  2. When you log in, it hashes what you typed and compares the two numbers
  3. The password itself is never written down anywhere

If the site's database leaks, the thief gets numbers. "Hard to invert" was on the list of properties earlier, and this is why.

Breaking in without the password

The login check compares two numbers. So the thief doesn't need your password. Any string with the same hash value gets in.

With a weak hash, that's easy. Our toy hash has only 2^64 outputs and no secret, and you'll find colliding names for an even simpler one in a few minutes.

With a strong hash it's meant to be impossible, but sometimes it stops being so. MD5 and SHA-1 were the standard for years, but both now have known collisions and are being phased out.

The everyday attack is simpler still: a good hash is fast, so a graphics card tries billions of guesses a second with common words. Sites defend with a hash built to be slow (bcrypt, Argon2) and a salt, a random string stored next to each hash, so cracking one person's password doesn't unlock everyone who chose the same one.

Rust's default hash for HashMap (and Python's for dict) are built for speed. Neither is a password-grade hash!

Activity 31, Rounds 2 to 4

See Activity 31.

Appendix: HashMap methods, the longer versions

Adding and updating

use std::collections::HashMap;

fn main() {
    let mut prices = HashMap::new();
    prices.insert("laptop".to_string(), 999.99);
    prices.insert("mouse".to_string(), 25.50);
    prices.insert("keyboard".to_string(), 75.00);

    // Same key again: overwrites
    prices.insert("laptop".to_string(), 899.99);

    // Only add if it isn't there yet
    if !prices.contains_key("tablet") {
        prices.insert("tablet".to_string(), 199.99);
    }

    // The same thing in one line
    prices.entry("tablet".to_string()).or_insert(199.99);

    println!("{:?}", prices);
}

.entry(key) finds the slot for a key, whether or not anything's in it yet. .or_insert(value) fills it if it was empty. We'll use it for counting in a few minutes.

Iterating on a HashMap

use std::collections::HashMap;

fn main() {
    let mut prices = HashMap::new();
    prices.insert("laptop".to_string(), 999.99);
    prices.insert("mouse".to_string(), 25.50);
    prices.insert("keyboard".to_string(), 75.00);

    // Both are references
    for (product, price) in prices.iter() {
        println!("{}: ${:.2}", product, price);
    }

    // 10% off everything. price is &mut
    // you can't get mut references to the keys
    for (_product, price) in prices.iter_mut() {
        *price = *price * 0.9;
    }

    for (product, price) in prices.iter() {
        println!("{}: ${:.2}", product, price);
    }
}

The order is random, and changes from one run to the next. It's whatever order the buckets happen to be in. Never write a test that depends on the order of items in a hashset/hashmap(/dict/set). If you need an order, collect the keys into a Vec and sort.

Counting things, the long way

How many times does each word appear?

use std::collections::HashMap;

fn main() {
    let text = "the cat sat on the mat";
    let mut word_counts = HashMap::new();

    for word in text.split_whitespace() {
        let new_count = match word_counts.get(word) {
            Some(count) => count + 1,
            None => 1,
        };
        word_counts.insert(word.to_string(), new_count);
    }

    for (word, count) in &word_counts {
        println!("'{}' appears {} times", word, count);
    }
}

Counting things, with entry

use std::collections::HashMap;

fn main() {
    let text = "the cat sat on the mat";
    let mut word_counts = HashMap::new();

    for word in text.split_whitespace() {
        let count = word_counts.entry(word.to_string()).or_insert(0);
        *count += 1;
    }

    for (word, count) in &word_counts {
        println!("'{}' appears {} times", word, count);
    }
}

.entry().or_insert(0) gives back a mutable reference to the value, whether it was just inserted or already there. Then *count += 1 writes through it, the way we wrote through &mut references a few weeks ago.

Appendix: borrow the values, or move them

Two ways to pour a Vec into a set:

use std::collections::HashSet;

fn main() {
    let names = vec![
        String::from("Alice"),
        String::from("Bob"),
        String::from("Alice"),
    ];

    // Option 1: clone each String. names is still usable
    let unique_names: HashSet<String> = names.iter().cloned().collect();
    println!("Original: {:?}", names);
    println!("Unique: {:?}", unique_names);

    // Option 2: move each String into the set. names is gone
    let unique_names: HashSet<String> = names.into_iter().collect();
    println!("Unique: {:?}", unique_names);
    // println!("{:?}", names);   // borrow of moved value
}
  • .iter().cloned() hands the set a copy of each element and leaves the Vec alone
  • .into_iter() hands over the elements themselves, and the Vec is consumed

Same choice as always: clone and keep both, or move and keep one.

Appendix: understanding .iter().cloned().collect()

let customers = vec!["Alice", "Bob", "Alice"];
let unique: HashSet<&str> = customers.iter().cloned().collect();

Step by step:

  1. .iter() makes an iterator over references to the elements. Each item is a &&str, a reference to a string slice
  2. .cloned() copies each item out from behind its reference. &&str becomes &str. For Copy types like &str and i32 this is just copying the pointer or the value
  3. .collect() gathers the items into whatever collection the type annotation names. Here that's HashSet<&str>, so duplicates are dropped on the way in

.into_iter() in place of .iter() gives the elements themselves, and the Vec can't be used afterwards. .iter().cloned() on a Vec<String> clones every string, which is a real cost; .into_iter() moves them for free.

Appendix: BTreeMap, the sorted cousin

std::collections has a second map, BTreeMap<K, V>, with the same insert, get, and entry. The difference is how it's stored: a balanced tree with the keys in sorted order, which gives O(log n) lookups in place of O(1).

This means iterating a BTreeMap visits the keys in order, every time, and you can ask for a range: every key between "M" and "N".

BTreeSet is to BTreeMap as HashSet is to HashMap. Keys need Ord, which we met in the traits lecture, in place of Hash and Eq.