实现说明
实际业务分支统一收拢于函数内部 window_slice、main,其余都是接线。
使用要点
- 整体编写天生免外部依赖——不查询外部注册表,也不会产生锁文件记录。
- 直接运行文件,输出会带上标签,比如
range [120..=150] count=、gap [160..=190] count=、beyond end count=——输出的每一行都能指回产生它的那次调用。 - 运行整个文件:
main会依次驱动window_slice。
常见问题
运行「用 slice::partition_point 二分截取有序区间切片」会打印什么?
整个文件跑完,输出行以 range [120..=150] count=、gap [160..=190] count=、beyond end count= 这类前缀开头。
主签名形如 fn window_slice(sorted: &[Metric], start: u64, end_incl: u64) -> &[Metric]
核心语句
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]
}
代码示例
#[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());
}