use core::cmp::Ordering;
use search_core::{Cost, WideMul};
#[derive(Debug, Clone, Copy)]
pub enum ApproxFactor<C> {
Zero,
Ratio {
num: C,
den: C,
},
Infinite,
}
impl<C: Cost + WideMul> ApproxFactor<C> {
#[must_use]
pub fn is_zero(self) -> bool {
matches!(self, Self::Zero)
}
#[must_use]
pub fn covers(self, x: C, y: C) -> bool {
if x <= y {
return true;
}
match self {
Self::Zero => false,
Self::Infinite => y > C::ZERO,
Self::Ratio { num, den } => x.abs_diff(y).wide_mul(den) <= num.wide_mul(y),
}
}
pub(crate) fn excess(by: C, of: C) -> Self {
if by <= of {
Self::Zero
} else if of == C::ZERO {
Self::Infinite
} else {
Self::Ratio {
num: by.abs_diff(of),
den: of,
}
}
}
pub(crate) fn domination(by: [C; 2], of: [C; 2]) -> Self {
Self::excess(by[0], of[0]).max(Self::excess(by[1], of[1]))
}
pub(crate) fn divided(self, d: u32) -> Self {
match self {
Self::Ratio { num, den } => {
let den = den.saturating_times(d);
if den.saturating_add(den) == den {
Self::Zero
} else {
Self::Ratio { num, den }
}
}
other => other,
}
}
}
impl<C: Cost + WideMul> PartialEq for ApproxFactor<C> {
fn eq(&self, other: &Self) -> bool {
self.cmp(other) == Ordering::Equal
}
}
impl<C: Cost + WideMul> Eq for ApproxFactor<C> {}
impl<C: Cost + WideMul> PartialOrd for ApproxFactor<C> {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl<C: Cost + WideMul> Ord for ApproxFactor<C> {
fn cmp(&self, other: &Self) -> Ordering {
match (*self, *other) {
(Self::Zero, Self::Zero) | (Self::Infinite, Self::Infinite) => Ordering::Equal,
(Self::Zero, _) | (_, Self::Infinite) => Ordering::Less,
(_, Self::Zero) | (Self::Infinite, _) => Ordering::Greater,
(Self::Ratio { num: a, den: b }, Self::Ratio { num: c, den: d }) => {
a.wide_mul(d).cmp(&c.wide_mul(b))
}
}
}
}
#[cfg(test)]
mod tests {
use super::ApproxFactor;
#[test]
fn order_is_numeric() {
let half = ApproxFactor::Ratio { num: 1_u32, den: 2 };
let two_quarters = ApproxFactor::Ratio { num: 2, den: 4 };
let third = ApproxFactor::Ratio { num: 1, den: 3 };
assert_eq!(half, two_quarters);
assert!(third < half);
assert!(ApproxFactor::Zero < third);
assert!(half < ApproxFactor::Infinite);
}
#[test]
fn domination_factor() {
let df = ApproxFactor::domination([2_u32, 3], [3, 2]);
assert_eq!(df, ApproxFactor::Ratio { num: 1, den: 2 });
assert!(ApproxFactor::domination([1_u32, 4], [1, 4]).is_zero());
assert_eq!(
ApproxFactor::domination([1_u32, 1], [1, 0]),
ApproxFactor::Infinite
);
}
#[test]
fn covers_is_exact() {
let half = ApproxFactor::Ratio { num: 1_u32, den: 2 };
assert!(half.covers(15, 10));
assert!(!half.covers(16, 10));
assert!(!ApproxFactor::Zero.covers(11_u32, 10));
assert!(ApproxFactor::Infinite.covers(100_u32, 1));
assert!(!ApproxFactor::Infinite.covers(1_u32, 0));
}
}