#![allow(unused_imports)]
use super::*;
#[derive(Clone)]
pub struct RcComparator<T> {
pub(super) function: Rc<dyn Fn(&T, &T) -> Ordering>,
}
impl<T> RcComparator<T> {
#[inline]
pub fn new<F>(f: F) -> Self
where
F: Fn(&T, &T) -> Ordering + 'static,
{
Self {
function: Rc::new(f),
}
}
#[inline]
pub fn reversed(&self) -> Self
where
T: 'static,
{
let self_fn = self.function.clone();
RcComparator::new(move |a, b| self_fn(b, a))
}
#[inline]
pub fn then_comparing(&self, other: &Self) -> Self
where
T: 'static,
{
let first = self.function.clone();
let second = other.function.clone();
RcComparator::new(move |a, b| match first(a, b) {
Ordering::Equal => second(a, b),
ord => ord,
})
}
#[inline]
pub fn comparing<K, F>(key_fn: F) -> Self
where
K: Ord,
F: Fn(&T) -> &K + 'static,
{
RcComparator::new(move |a, b| 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 RcComparator<T> {
#[inline]
fn compare(&self, a: &T, b: &T) -> Ordering {
(self.function)(a, b)
}
}