skip to content

How does Rust's BinaryHeap::peek_mut let you change the top element in place, and when is the heap invariant restored?

level: seniorimportance: should knowfreq 30%

answer

  1. a guard, not a bare &mut
  2. Drop does the repair
  3. sift down once
  4. PeekMut::pop, leak amplification

basics

~20 s

peek_mut returns a PeekMut guard that derefs to the top element. If you write through it, the guard's Drop sifts that element down, so the heap is repaired once, when the guard goes out of scope.

solid answer

~40 s

`BinaryHeap::peek_mut` returns `Option<PeekMut<'_, T>>`, a guard holding `&mut` to the heap. `Deref` reads the top; `DerefMut` records that it may change; when the guard drops, it sifts element 0 down, costing O(log n) if modified and O(1) otherwise. That beats `pop` then `push`, which sifts twice. `PeekMut::pop(guard)` removes the top through the same handle. While the guard lives, the heap is mutably borrowed, so calling `heap.push` meanwhile fails with E0499. Since Rust 1.68 a leaked guard cannot corrupt the heap: the first mutable access shrinks the length to 1 until drop restores it, so `mem::forget` leaks the rest but leaves a valid heap. Changing other elements' order through a `Cell` is a logic error, not UB.

code

rust · 22 lines
rust
use std::collections::BinaryHeap;
use std::collections::binary_heap::PeekMut;

fn main() {
    // (priority, job id): the max-heap serves the highest priority first.
    let mut heap = BinaryHeap::from([(9, "reindex"), (5, "email"), (7, "thumbnail")]);

    // Demote the top job in place instead of pop + push.
    if let Some(mut top) = heap.peek_mut() {
        top.0 = 1; // PeekMut's Drop sifts the new value down
    }
    println!("after demotion, top = {:?}", heap.peek());

    // Conditionally remove the top through the same handle.
    if let Some(top) = heap.peek_mut() {
        if top.1 == "thumbnail" {
            let job = PeekMut::pop(top);
            println!("popped {job:?}");
        }
    }
    println!("sorted rest: {:?}", heap.into_sorted_vec());
}

go deeper

for a junior

Know that peek shows the top and peek_mut lets you change it, and that the heap fixes itself after you are done.

for a middle

Explain the guard: Deref to read, DerefMut to write, Drop to sift down, plus PeekMut::pop for conditional removal.

for a senior

Connect the borrow to soundness (E0499 keeps the heap unobservable), describe leak amplification since 1.68, and separate logic errors from undefined behaviour.

for a principal

Use this API as the model for guarded mutation in your own containers: hand out a guard whose Drop restores the invariant, and stay valid if it leaks.

## The problem `peek_mut` solves A scheduler often wants to change the job at the top of a `BinaryHeap` — demote it, bump its retry count, push its deadline out — without removing it. The naive way is `let mut top = heap.pop().unwrap(); top.0 = 1; heap.push(top);`, which sifts twice. `BinaryHeap::peek_mut` gives you a mutable handle to the top element and **one** repair at the end. You cannot simply get a `&mut T` to the top, because writing through it could break the **heap invariant** (every parent compares greater than or equal to its children), and the heap would never know. So `peek_mut` returns `Option<PeekMut<'_, T>>`, a guard type, and the guard decides when to repair. ## How `PeekMut` works `PeekMut` holds a `&mut BinaryHeap<T>` and implements three traits that matter: - **`Deref<Target = T>`** — reading `*top` or `top.field` is plain access to element 0. - **`DerefMut`** — the first mutable access records that the top may have changed. - **`Drop`** — when the guard goes out of scope, if a mutable access happened, it **sifts element 0 down** to its proper place. std documents the cost: O(log n) in the worst case if the item is modified, O(1) otherwise. In current std the decision rests on whether `DerefMut` was used on a heap of more than one element, not on comparing old and new values. `PeekMut::pop(guard)`, an associated function rather than a method, removes the top through the same handle — useful for "look, then decide whether to take it". ## What the borrow checker adds Because `PeekMut` holds `&mut heap`, the heap cannot be used while the guard lives. `heap.push(3)` while a `PeekMut` is still used later fails with **E0499**: "cannot borrow `heap` as mutable more than once at a time". This is what makes the scheme sound: nobody can observe the heap between the write and the repair. Scope the guard tightly with `if let Some(mut top) = heap.peek_mut() { ... }`, or `drop(top)` explicitly. ## What if the guard is leaked `mem::forget` is safe Rust, so a `PeekMut` might never be dropped and its repair never run. Since **Rust 1.68**, std defends against this with **leak amplification**: on the first mutable access, `DerefMut` temporarily sets the heap's length to 1, and `Drop` or `PeekMut::pop` restores it. If the guard is forgotten, the other elements are leaked but the heap that remains is valid. The doc comment on `peek_mut` says so: some heap elements might get leaked, "but the remaining elements will remain a valid heap". In a test, a four-element heap written through and forgotten reports `len() == 1`. ## Where the invariant can still break `PeekMut` only covers the top element. std calls it a **logic error** to modify any element so that its ordering relative to the others changes while it is in the heap, which is normally only possible through interior mutability such as `Cell` or `RefCell`, global state, I/O, or unsafe code. The result is unspecified — panics, wrong results, aborts, leaks or non-termination — but std promises it stays **encapsulated to that heap and is not undefined behaviour**. ## Choosing between the options | Goal | Tool | Sifts | |---|---|---| | Change the top element | `peek_mut`, write, drop the guard | one sift-down | | Conditionally remove the top | `peek_mut` then `PeekMut::pop` | one | | Change any other element | rebuild or remove and re-push | not supported in place | | Change the top, then reinsert | `pop` then `push` | two | Practical guidance: 1. Keep the guard's scope to the few lines that read and write the top. 2. Never stash a `PeekMut` in a struct; it borrows the heap for its whole life. 3. Do not mutate keys through shared references or cells while they are queued. 4. Remember that `peek_mut` sits behind a `T: Ord` bound, like `push` and `pop`, because its guard must compare elements when it sifts.

  • Why is peek_mut cheaper than pop followed by push?
    `pop` moves the last element to the root and sifts it down, then `push` appends and sifts up, so two repairs touch the tree. `peek_mut` changes the root in place and its guard sifts down once on drop. If you never write through the guard, there is no repair at all, so it is O(1).
  • Can you hold a PeekMut and push a new job onto the same heap at the same time?
    No. The guard holds a mutable borrow of the heap, so `heap.push` while the guard is still used later fails with E0499. End the guard's scope or call `drop(top)` first; the drop runs the sift, and then the heap is free to borrow again.

  • The heap re-sorts itself on every assignment through the reference.
  • peek_mut returns a plain &mut T to the largest element.
  • Forgetting a PeekMut with mem::forget causes undefined behaviour.
  • Mutating a queued element through a RefCell is undefined behaviour.
  • You can push to the heap while the PeekMut guard is alive.

Assumes Rust 1.99; peek_mut dates from 1.12 and PeekMut::pop from 1.18, and leak amplification for a forgotten PeekMut was added in Rust 1.68.