Slice Sorted Ranges With partition_point
Pair two slice::partition_point binary lookups for lower and upper bounds to extract an O(log n) contiguous range slice from sorted structs.
Code
#[derive(Debug)]
struct Metric {
ts: u64,
value: u32,
}
fn window_slice(sorted: &[Metric], start: u64, end_incl: u64) -> &[Metric] {
if start > end_incl {
return &[];
}
let lo = sorted.partition_point(|m| m.ts < start);
let hi = sorted.partition_point(|m| m.ts <= end_incl);
&sorted[lo..hi]
}
fn main() {
let series = [
Metric { ts: 100, value: 4 },
Metric { ts: 120, value: 7 },
Metric { ts: 120, value: 9 },
Metric { ts: 150, value: 12 },
Metric { ts: 200, value: 5 },
];
let hits = window_slice(&series, 120, 150);
println!("range [120..=150] count={}: {hits:?}", hits.len());
let empty = window_slice(&series, 160, 190);
println!("gap [160..=190] count={}", empty.len());
let all_after = window_slice(&series, 250, 300);
println!("beyond end count={}", all_after.len());
}Execution path — Slice Sorted Ranges With partition_point
Structurally, expect the functions window_slice and main and nothing else.
Caveats
- Ready for immediate execution without adding packages to your project.
Putting it to use
Entry signature: fn window_slice(sorted: &[Metric], start: u64, end_incl: u64) -> &[Metric]
The file’s steps show up in the output as range [120..=150] count=, gap [160..=190] count=, beyond end count=.
main is the driver: it invokes window_slice before returning.
Core lines
fn window_slice(sorted: &[Metric], start: u64, end_incl: u64) -> &[Metric] {
if start > end_incl {
return &[];
}
let lo = sorted.partition_point(|m| m.ts < start);
let hi = sorted.partition_point(|m| m.ts <= end_incl);
&sorted[lo..hi]
}
Interactive Tools for This Topic
Big-O Complexity VisualizerVisualize and compare algorithm time complexities like O(1), O(log n), O(n), O(n log n), and O(n²). Plot growth curves to understand performance scaling at a glance.Binary Text ConverterConvert UTF-8 text to 8-bit binary groups and decode binary back to text with strict validation.Bitwise Operations CalculatorCompute AND, OR, XOR, NOT, and shifts on 32-bit unsigned operands with binary, hex, and signed decimal views.Fuzzy Match TesterTest subsequence fuzzy matching: check whether pattern characters appear in order inside a text, with positions and highlighting.
FAQ
- What does Slice Sorted Ranges With partition_point print when run?
- No setup needed: run the file and look for labeled lines like `range [120..=150] count=`, `gap [160..=190] count=`, `beyond end count=` in the output.
Report a problem with this exampleOpens a pre-filled issue on GitHub.