BTreeMap Sorted Snapshot Report

Aggregate hits in a BTreeMap whose natural key order makes reports deterministic, with range iteration and entry upserts and no explicit sorting step.

RustData Integrity

Code

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

fn main() {
    // BTreeMap keeps keys sorted:遍历天然按键序,快照报表无需再排序
    let mut hits: BTreeMap<String, u32> = BTreeMap::new();
    for path in ["/b", "/a", "/c", "/a", "/b", "/a"] {
        *hits.entry(path.to_string()).or_insert(0) += 1;
    }

    // 范围迭代:只取 a..d 之间的路径,仍保持有序
    let within: Vec<(String, u32)> = hits
        .range("a".to_string().."d".to_string())
        .map(|(k, v)| (k.clone(), *v))
        .collect();
    println!("a..d entries: {:?}", within);

    // 全量快照输出:顺序稳定,可直接做 golden 对比
    let mut total = 0;
    for (path, count) in &hits {
        println!("{} {}", count, path);
        total += count;
    }
    println!("total {}", total);
}

How it works

The moving parts are the function main.

Iteration happens inside for path in ["/b", "/a", "/c", "/a", "/b", "/a"] — everything outside it runs once.

Points of care

  • No dependencies section needed; the standard library is the whole story.

Using it

The primary signature is fn main()

Output lines are prefixed (a..d entries:, total), making each step’s effect easy to spot.

Key statements

total += count;
.map(|(k, v)| (k.clone(), *v))
.collect();

Interactive Tools for This Topic

FAQ

What does BTreeMap Sorted Snapshot Report print when run?
Execute the whole file; each printed line is prefixed with a label like `a..d entries:`, `total`.