pub trait ToKey<KeyType> {
fn to_key(&self) -> KeyType;
}
pub struct RangedMap<Key, Val> where Key: Ord + Copy, Val: ToKey<Key> + Copy {
map: std::collections::BTreeMap<Key, Val>,
}
impl<Key, Val> RangedMap<Key, Val> where Key: Ord + Copy, Val: ToKey<Key> + Copy {
pub fn new() -> RangedMap<Key, Val> {
RangedMap { map: std::collections::BTreeMap::new() }
}
pub fn get_neighbors_to(&self, point: Key) -> (Val, Val) {
let p1 = self.iter().rev().find(|&(&k, &_)| { k <= point }).expect("Couldn't find any preceding or equal point");
let p2 = self.iter() .find(|&(&k, &_)| { k > point }).expect("Couldn't find following point");
(*p1.1, *p2.1)
}
pub fn get_2nd_neighbors_to(&self, point: Key) -> (Val, Val, Val, Val) {
let (inner_1, inner_2) = self.get_neighbors_to(point);
let outer_1 = self.iter().rev().find(|&(&k, &_)| { k < inner_1.to_key() }).expect("Couldn't find any preceding point").1;
let outer_2 = self.iter() .find(|&(&k, &_)| { k > inner_2.to_key() }).expect("Couldn't find any following point").1;
(*outer_1, inner_1, inner_2, *outer_2)
}
}
impl<Key, Val> std::ops::Deref for RangedMap<Key, Val> where Key: Ord + Copy, Val: ToKey<Key> + Copy {
type Target = std::collections::BTreeMap<Key, Val>;
fn deref(&self) -> &Self::Target {
&self.map
}
}
impl<Key, Val> std::ops::DerefMut for RangedMap<Key, Val> where Key: Ord + Copy, Val: ToKey<Key> + Copy {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.map
}
}