Skip to content

Commit 0421fb0

Browse files
committed
Added upper/lower_bound on slices
1 parent f5c3543 commit 0421fb0

File tree

1 file changed

+34
-2
lines changed

1 file changed

+34
-2
lines changed

src/range_query/mod.rs

Lines changed: 34 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,9 +6,25 @@ pub use dynamic_arq::{ArqView, DynamicArq};
66
pub use specs::ArqSpec;
77
pub use static_arq::StaticArq;
88

9+
/// Assuming slice is sorted, returns the minimum i for which slice[i] >= key,
10+
/// or slice.len() if no such i exists
11+
pub fn slice_lower_bound<T: Ord>(slice: &[T], key: &T) -> usize {
12+
slice
13+
.binary_search_by(|x| x.cmp(key).then(std::cmp::Ordering::Greater))
14+
.unwrap_err()
15+
}
16+
17+
/// Assuming slice is sorted, returns the minimum i for which slice[i] > key,
18+
/// or slice.len() if no such i exists
19+
pub fn slice_upper_bound<T: Ord>(slice: &[T], key: &T) -> usize {
20+
slice
21+
.binary_search_by(|x| x.cmp(key).then(std::cmp::Ordering::Less))
22+
.unwrap_err()
23+
}
24+
925
/// A simple data structure for coordinate compression
1026
pub struct SparseIndex {
11-
coords: Vec<i64>
27+
coords: Vec<i64>,
1228
}
1329

1430
impl SparseIndex {
@@ -31,6 +47,22 @@ mod test {
3147
use super::specs::*;
3248
use super::*;
3349

50+
#[test]
51+
fn test_bounds() {
52+
let mut vals = vec![16, 45, 45, 45, 82];
53+
54+
assert_eq!(slice_upper_bound(&vals, &44), 1);
55+
assert_eq!(slice_lower_bound(&vals, &45), 1);
56+
assert_eq!(slice_upper_bound(&vals, &45), 4);
57+
assert_eq!(slice_lower_bound(&vals, &46), 4);
58+
59+
vals.dedup();
60+
for (i, q) in vals.iter().enumerate() {
61+
assert_eq!(slice_lower_bound(&vals, q), i);
62+
assert_eq!(slice_upper_bound(&vals, q), i + 1);
63+
}
64+
}
65+
3466
#[test]
3567
fn test_coord_compress() {
3668
let mut coords = vec![16, 99, 45, 18];
@@ -49,7 +81,7 @@ mod test {
4981
let queries = vec![(0, 10), (10, 19), (20, 29)];
5082
let coords = queries.iter().flat_map(|&(i, j)| vec![i, j + 1]).collect();
5183
let index = SparseIndex::new(coords);
52-
84+
5385
assert_eq!(index.coords, vec![0, 10, 11, 20, 30]);
5486
}
5587

0 commit comments

Comments
 (0)