BTreeMap Pop First Drains In Order

Drain a BTreeMap deadline queue in key order with pop_first, and pop_last for reverse audit passes, consuming entries as they are taken.

RustResilience

Code

rustsnippet
22 lines
use std::collections::BTreeMap;

fn main() {
    let mut deadlines: BTreeMap<u64, &str> = BTreeMap::new();
    deadlines.insert(30, "flush-wal");
    deadlines.insert(10, "send-heartbeat");
    deadlines.insert(20, "compact-segments");

    // pop_first 按 key 从小到大逐个消费:到期任务先跑
    while let Some((at, job)) = deadlines.pop_first() {
        println!("run @{at}: {job}");
    }
    println!("after drain: {}", deadlines.len());

    deadlines.insert(5, "checkpoint");
    deadlines.insert(15, "rotate-keys");

    // pop_last 反向:逆序审计、或先处理剩余时间最长的
    while let Some((at, job)) = deadlines.pop_last() {
        println!("reverse @{at}: {job}");
    }
}

Inside the code

The snippet is organized around the function main.

Repetition is confined to while let Some((at, job)) = deadlines.pop_first() — the rest of the file is straight-line.

Points of care

  • Ready as-is on a bare install of the language.

Applying it

Entry signature: fn main()

Look for the run @, after drain:, reverse @ prefixes during the file’s run; they bind each line to the step behind it.

Statements that matter

while let Some((at, job)) = deadlines.pop_first() {
    println!("run @{at}: {job}");
}
while let Some((at, job)) = deadlines.pop_last() {
    println!("reverse @{at}: {job}");
}

Interactive Tools for This Topic

FAQ

What does BTreeMap Pop First Drains In Order print when run?
The script runs standalone; its 3 labeled outputs include `run @`, `after drain:`, `reverse @`.