pub trait Comparator<T: ?Sized> {
// Required method
fn cmp(&self, left: &T, right: &T) -> Ordering;
// Provided methods
fn reversed(self) -> ReversedOrder<T, Self>
where Self: Sized { ... }
fn then<N>(self, next: N) -> CompareThen<T, Self, N>
where Self: Sized,
N: Comparator<T> { ... }
fn max<'a>(&self, left: &'a T, right: &'a T) -> &'a T { ... }
fn min<'a>(&self, left: &'a T, right: &'a T) -> &'a T { ... }
}
Expand description
Implementations define a linear ordering over the type T
, which can be semantically
different from Ord::cmp
.
By convention, the ordering should fulfill the following properties
(for all a
, b
and c
):
- connex:
a <= b
orb <= a
- antisymmetric: if
a <= b
andb <= a
thena == b
- transitive: if
a <= b
andb <= c
thena <= c
(where a <= b
can be also understood as !(a > b)
)
§Examples
use std::cmp::Ordering;
use classific::{Comparator, comparing, natural_order, reverse_order};
assert_eq!(natural_order().cmp(&1, &2), Ordering::Less);
assert_eq!(comparing(|v| v & !3).cmp(&1, &2), Ordering::Equal);
assert_eq!(reverse_order().cmp(&1, &2), Ordering::Greater);
Required Methods§
Sourcefn cmp(&self, left: &T, right: &T) -> Ordering
fn cmp(&self, left: &T, right: &T) -> Ordering
This method returns an Ordering
between left
and right
.
By convention, comparator.cmp(&left, &right)
returns the ordering matching the expression
left <operator> right
if true.
§Examples
use std::cmp::Ordering;
use classific::{Comparator, comparing, natural_order, reverse_order};
assert_eq!(natural_order().cmp(&1, &2), Ordering::Less);
assert_eq!(comparing(|v| v & !3).cmp(&1, &2), Ordering::Equal);
assert_eq!(reverse_order().cmp(&1, &2), Ordering::Greater);
Provided Methods§
Sourcefn reversed(self) -> ReversedOrder<T, Self>where
Self: Sized,
fn reversed(self) -> ReversedOrder<T, Self>where
Self: Sized,
This method returns a Comparator
which is semantically reversed from self
.
The ordering of the result Comparator
will fulfill the following
(for all a
, b
):
use classific::Comparator;
fn test<T>(a: &T, b: &T, comparator: impl Comparator<T>) {
assert_eq!(comparator.cmp(a, b).reverse(), comparator.reversed().cmp(a, b));
}
Sourcefn then<N>(self, next: N) -> CompareThen<T, Self, N>where
Self: Sized,
N: Comparator<T>,
fn then<N>(self, next: N) -> CompareThen<T, Self, N>where
Self: Sized,
N: Comparator<T>,
This method returns a Comparator
which is further refining the semantics of self
.
next::cmp
is called only when self::cmp
returns Ordering::Equal
.
§Examples
use std::cmp::Ordering;
use classific::{Comparator, comparing, natural_order, reverse_order};
assert_eq!(comparing(|t: &(i8, i8)| t.0).then(comparing(|t: &(i8, i8)| t.1)).cmp(&(1, 2), &(1, 3)), Ordering::Less);