Inspect And Pop Extremes With BTreeMap::first_entry
Use BTreeMap::first_entry and last_entry to read, mutate, and evict minimum or maximum key buckets in place through OccupiedEntry without re-lookup.
Code
use std::collections::BTreeMap;
fn drain_due(schedule: &mut BTreeMap<u64, Vec<&'static str>>, cutoff: u64) -> Vec<&'static str> {
let mut due = Vec::new();
while let Some(entry) = schedule.first_entry() {
if *entry.key() > cutoff {
break;
}
let (_, mut jobs) = entry.remove_entry();
due.append(&mut jobs);
}
due
}
fn pop_next_job(schedule: &mut BTreeMap<u64, Vec<&'static str>>) -> Option<(u64, &'static str)> {
let mut entry = schedule.first_entry()?;
let ts = *entry.key();
let job = entry.get_mut().remove(0);
if entry.get().is_empty() {
entry.remove_entry();
}
Some((ts, job))
}
fn main() {
let mut schedule: BTreeMap<u64, Vec<&'static str>> = BTreeMap::new();
schedule.insert(10, vec!["cleanup"]);
schedule.insert(25, vec!["email", "webhook"]);
schedule.insert(40, vec!["snapshot"]);
schedule.insert(90, vec!["archive"]);
println!("due <= 15: {:?}", drain_due(&mut schedule, 15));
println!("next job: {:?}", pop_next_job(&mut schedule));
if let Some(last) = schedule.last_entry() {
let (ts, dropped) = last.remove_entry();
println!("trimmed furthest bucket ts={ts}: {dropped:?}");
}
println!("remaining buckets: {schedule:?}");
}Step-by-step analysis — Inspect And Pop Extremes With BTreeMap::first_entry
The code’s whole job belongs to the functions drain_due, pop_next_job and main.
The file repeats itself only inside while let Some(entry) = schedule.first_entry().
Points of care
- Works out of the box using only bundled toolchain libraries — nothing additional needed.
Putting it to use
The entry-point signature is fn drain_due(schedule: &mut BTreeMap<u64, Vec<&'static str>>, cutoff: u64) -> Vec<&'static str>
Terminal records arrive marked by — due <= 15:, next job:, trimmed furthest bucket ts= — when the file runs.
Launch the file; main takes over and steps through drain_due and pop_next_job.
Core lines
while let Some(entry) = schedule.first_entry() {
if *entry.key() > cutoff {
break;
}
let (_, mut jobs) = entry.remove_entry();
due.append(&mut jobs);
}
fn pop_next_job(schedule: &mut BTreeMap<u64, Vec<&'static str>>) -> Option<(u64, &'static str)> {
let mut entry = schedule.first_entry()?;
let ts = *entry.key();
let job = entry.get_mut().remove(0);
if entry.get().is_empty() {
entry.remove_entry();
}
Some((ts, job))
}
if let Some(last) = schedule.last_entry() {
let (ts, dropped) = last.remove_entry();
println!("trimmed furthest bucket ts={ts}: {dropped:?}");
}
Interactive Tools for This Topic
FAQ
- What does Inspect And Pop Extremes With BTreeMap::first_entry print when run?
- The script runs standalone; its 4 labeled outputs include `due <= 15:`, `next job:`, `trimmed furthest bucket ts=`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.