47 lines
1.2 KiB
Rust
47 lines
1.2 KiB
Rust
/// Result returned by [`Comparator::compare`].
|
|
#[derive(Debug, PartialEq)]
|
|
pub enum Comparison {
|
|
L,
|
|
/// Compared values were equal.
|
|
E,
|
|
R,
|
|
}
|
|
|
|
/// Returns [`Comparison`] saying which value is smaller.
|
|
///
|
|
/// ```rust
|
|
/// # use radn_rs::flow::comparator::*;
|
|
/// assert_eq!(DefaultComparator.compare(&1, &3), Comparison::L);
|
|
/// assert_eq!(DefaultComparator.compare(&2, &2), Comparison::E);
|
|
/// assert_eq!(DefaultComparator.compare(&3, &1), Comparison::R);
|
|
/// ```
|
|
pub trait Comparator<A> {
|
|
fn compare(&self, kl: &A, kr: &A) -> Comparison;
|
|
}
|
|
|
|
/// Implementation of a [Comparator] relying on [`Ord`].
|
|
pub struct DefaultComparator;
|
|
|
|
impl<A: Ord> Comparator<A> for DefaultComparator {
|
|
fn compare(&self, kl: &A, kr: &A) -> Comparison {
|
|
match kl.cmp(kr) {
|
|
std::cmp::Ordering::Less => Comparison::L,
|
|
std::cmp::Ordering::Equal => Comparison::E,
|
|
std::cmp::Ordering::Greater => Comparison::R,
|
|
}
|
|
}
|
|
}
|
|
|
|
pub struct RcComparator<C>(C);
|
|
|
|
mod rc_comparator_impl {
|
|
use super::*;
|
|
use std::rc::Rc;
|
|
|
|
impl<A, C: Comparator<A>> Comparator<Rc<A>> for RcComparator<C> {
|
|
fn compare(&self, kl: &Rc<A>, kr: &Rc<A>) -> Comparison {
|
|
self.0.compare(kl, kr)
|
|
}
|
|
}
|
|
}
|