#![allow(unused_imports)]
use super::*;
pub struct BoxComparator<T> {
pub(super) function: Box<dyn Fn(&T, &T) -> Ordering>,
}
impl<T> BoxComparator<T> {
#[inline]
pub fn new<F>(f: F) -> Self
where
F: Fn(&T, &T) -> Ordering + 'static,
{
Self {
function: Box::new(f),
}
}
#[inline]
pub fn reversed(self) -> Self
where
T: 'static,
{
BoxComparator::new(move |a, b| (self.function)(b, a))
}
#[inline]
pub fn then_comparing(self, other: Self) -> Self
where
T: 'static,
{
BoxComparator::new(move |a, b| match (self.function)(a, b) {
Ordering::Equal => (other.function)(a, b),
ord => ord,
})
}
#[inline]
pub fn comparing<K, F>(key_fn: F) -> Self
where
K: Ord,
F: Fn(&T) -> &K + 'static,
{
BoxComparator::new(move |a: &T, b: &T| key_fn(a).cmp(key_fn(b)))
}
#[inline]
pub fn into_fn(self) -> impl Fn(&T, &T) -> Ordering {
move |a: &T, b: &T| (self.function)(a, b)
}
}
impl<T> Comparator<T> for BoxComparator<T> {
#[inline]
fn compare(&self, a: &T, b: &T) -> Ordering {
(self.function)(a, b)
}
}