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.

RustData Integrity

Code

snippet
#[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

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.