In Rust, you can extend the functionality of existing types by using traits. To make interval_search a method for any vector of tuples in the form (T, T), where T can be any type that supports comparison (e.g., numbers), you can define a trait and implement it for Vec<(T, T)>. For simplicity and because u64 was used in your original function, we'll stick to that, but I'll also explain how you could generalize it for other types.
First, let's define a trait named IntervalSearch and implement it for Vec<(u64, u64)>:
trait IntervalSearch {
fn interval_search(&self, query: &(u64, u64)) -> Option<(u64, u64)>;
}
impl IntervalSearch for Vec<(u64, u64)> {
fn interval_search(&self, query: &(u64, u64)) -> Option<(u64, u64)> {
let mut start = 0;
let mut end = self.len();
while start < end {
let mid = start + (end - start) / 2;
let mid_val = self[mid];
if query.1 <= mid_val.0 {
end = mid;
} else if query.0 >= mid_val.1 {
start = mid + 1;
} else {
return Some(mid_val);
}
}
None
}
}
Now, with IntervalSearch trait implemented for Vec<(u64, u64)>, you can do exactly what you asked for:
fn main() {
let x = vec![(1,6), (10,15), (25,32)];
let y = (26,30);
match x.interval_search(&y) {
Some(interval) => println!("Found interval: {:?}", interval),
None => println!("No overlapping interval found"),
}
}
Generalizing for Any Numeric Type
If you'd like this to work with any numeric type, not just u64, you can use Rust's generic types and traits. Here's a more generic approach using the PartialOrd trait, which allows for comparison operations. This way, your method can support any numeric type that can be compared:
trait IntervalSearch<T> {
fn interval_search(&self, query: &(T, T)) -> Option<(T, T)>
where
T: PartialOrd + Copy;
}
impl<T> IntervalSearch<T> for Vec<(T, T)> {
fn interval_search(&self, query: &(T, T)) -> Option<(T, T)>
where
T: PartialOrd + Copy,
{
let mut start = 0;
let mut end = self.len();
while start < end {
let mid = start + (end - start) / 2;
let mid_val = self[mid];
if query.1 <= mid_val.0 {
end = mid;
} else if query.0 >= mid_val.1 {
start = mid + 1;
} else {
return Some(mid_val);
}
}
None
}
}
Notice the T: PartialOrd + Copy constraint. PartialOrd allows for the comparison operations needed to check the intervals, and Copy ensures that types that implement this trait can be easily copied, which is required because we're returning tuple values directly.
With this generic approach, your methodology can apply to vectors of intervals consisting of i32, f64, or any other types that implement PartialOrd and Copy, making it much more flexible.