Slice Time Buckets Using BTreeMap::range
Query ordered timestamp keys in BTreeMap using half-open ranges, inclusive aggregates, and Bound::Excluded for strict cursor resumption.
Code
use std::collections::BTreeMap;
use std::ops::Bound::{Excluded, Included};
fn main() {
let buckets = BTreeMap::from([
(1000_u64, 12_u32),
(1060, 18),
(1120, 9),
(1180, 25),
(1240, 14),
]);
// Half-open [1060, 1240)
let window: Vec<_> = buckets.range(1060..1240).collect();
println!("half-open [1060..1240): {window:?}");
// Inclusive [1060, 1240]
let total: u32 = buckets.range(1060..=1240).map(|(_, v)| v).sum();
println!("inclusive sum [1060..=1240]: {total}");
// Strict cursor resume after key 1120 using explicit Bound
let after_cursor: Vec<_> = buckets.range((Excluded(1120_u64), Included(1240_u64))).collect();
println!("strictly after 1120: {after_cursor:?}");
}Stepwise trace — Slice Time Buckets Using BTreeMap::range
Slice Time Buckets Using BTreeMap::range is built around the function main.
Caveats
- Zero external dependencies required; standard library constructs carry all work.
Putting it to use
The entry-point signature is fn main()
The demo output is labeled (half-open [1060..1240):, inclusive sum [1060..=1240]:, strictly after 1120:); each label names the call that printed it.
Core lines
let total: u32 = buckets.range(1060..=1240).map(|(_, v)| v).sum();
let after_cursor: Vec<_> = buckets.range((Excluded(1120_u64), Included(1240_u64))).collect();
let window: Vec<_> = buckets.range(1060..1240).collect();
Interactive Tools for This Topic
Duration ConverterConvert between human durations like 1w2d3h45m and total seconds, hours, and minutes with negative support.Duration HumanizerTurn a number of seconds into a readable duration such as 1 day, 2 hours, 3 minutes, and show the equivalent in minutes and hours.ISO 8601 Duration ParserParse ISO 8601 durations like PT1H30M into year, month, week, day, and time components with exact or approximate total seconds.SemVer Range CheckerCheck whether a semantic version satisfies an npm-style range such as caret, tilde, comparison sets, wildcards, or hyphen ranges.
FAQ
- What does Slice Time Buckets Using BTreeMap::range print when run?
- Execute the whole file; each printed line is prefixed with a label like `half-open [1060..1240):`, `inclusive sum [1060..=1240]:`, `strictly after 1120:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.