use std::cmp::Ordering;
const SLACK_RATIO: f32 = 1e-3;
const SLACK_PT: f32 = 1e-2;
pub(crate) struct Band {
order: Vec<usize>,
keys: Vec<f32>,
}
impl Band {
pub(crate) fn new(keys: impl IntoIterator<Item = f32>) -> Self {
let keys: Vec<f32> = keys.into_iter().collect();
let mut order: Vec<usize> = (0..keys.len()).collect();
order.sort_by(|&a, &b| keys[a].total_cmp(&keys[b]));
let keys = order.iter().map(|&index| keys[index]).collect();
Self { order, keys }
}
pub(crate) fn within(&self, low: f32, high: f32) -> &[usize] {
let margin = (high - low).abs() * SLACK_RATIO + SLACK_PT;
let (low, high) = (low - margin, high + margin);
if !matches!(low.partial_cmp(&high), Some(Ordering::Less | Ordering::Equal)) {
return &self.order;
}
let start = self.keys.partition_point(|key| key.total_cmp(&low).is_lt());
let end = self.keys.partition_point(|key| key.total_cmp(&high).is_le());
&self.order[start..end.max(start)]
}
pub(crate) fn around(&self, at: f32, reach: f32) -> &[usize] {
self.within(at - reach, at + reach)
}
}
#[cfg(test)]
mod tests {
use super::Band;
#[test]
fn a_band_holds_the_items_within_it_by_coordinate_then_order() {
let band = Band::new([5.0, 1.0, 3.0, 1.0, 9.0]);
assert_eq!(band.within(1.0, 3.0), &[1, 3, 2]);
assert_eq!(band.around(5.0, 0.5), &[0]);
assert!(band.within(6.0, 8.0).is_empty());
assert_eq!(band.within(f32::NAN, 1.0).len(), 5);
assert_eq!(band.around(0.1 + 0.2, 4.7), &[1, 3, 2, 0]);
}
}