use crate::{repr::Repr, RBig, Relaxed};
use core::{
cmp::Ordering,
hash::{Hash, Hasher},
};
use dashu_base::{BitTest, Sign::*};
impl PartialEq for Repr {
#[inline]
fn eq(&self, other: &Self) -> bool {
if self.numerator.sign() != other.numerator.sign() {
return false;
}
if self.numerator.is_zero() {
return other.numerator.is_zero();
}
let n1d2_bits = self.numerator.bit_len() as isize + other.denominator.bit_len() as isize;
let n2d1_bits = other.numerator.bit_len() as isize + self.denominator.bit_len() as isize;
if n1d2_bits.abs_diff(n2d1_bits) > 1 {
return false;
}
(&self.numerator) * (&other.denominator) == (&other.numerator) * (&self.denominator)
}
}
impl Eq for Repr {}
impl PartialEq for RBig {
#[inline]
fn eq(&self, other: &Self) -> bool {
self.0.numerator == other.0.numerator && self.0.denominator == other.0.denominator
}
}
impl Eq for RBig {}
impl Hash for RBig {
#[inline]
fn hash<H: Hasher>(&self, state: &mut H) {
self.0.numerator.hash(state);
self.0.denominator.hash(state);
}
}
impl PartialOrd for Repr {
#[inline]
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl Ord for Repr {
fn cmp(&self, other: &Self) -> Ordering {
let negative = match (self.numerator.sign(), other.numerator.sign()) {
(Positive, Positive) => false,
(Positive, Negative) => return Ordering::Greater,
(Negative, Positive) => return Ordering::Less,
(Negative, Negative) => true,
};
if self.denominator.is_one() && other.denominator.is_one() {
return self.numerator.cmp(&other.numerator);
}
match (self.numerator.is_zero(), other.numerator.is_zero()) {
(true, true) => return Ordering::Equal,
(true, false) => return Ordering::Less, (false, true) => return Ordering::Greater, _ => {}
};
let n1d2_bits = self.numerator.bit_len() as isize + other.denominator.bit_len() as isize;
let n2d1_bits = other.numerator.bit_len() as isize + self.denominator.bit_len() as isize;
if n1d2_bits > n2d1_bits + 1 {
return if negative {
Ordering::Less
} else {
Ordering::Greater
};
} else if n1d2_bits < n2d1_bits - 1 {
return if negative {
Ordering::Greater
} else {
Ordering::Less
};
}
let n1d2 = (&self.numerator) * (&other.denominator);
let n2d1 = (&other.numerator) * (&self.denominator);
n1d2.cmp(&n2d1)
}
}
impl PartialEq<RBig> for Relaxed {
#[inline]
fn eq(&self, other: &RBig) -> bool {
self.0.eq(&other.0)
}
}
impl PartialOrd<RBig> for Relaxed {
#[inline]
fn partial_cmp(&self, other: &RBig) -> Option<Ordering> {
self.0.partial_cmp(&other.0)
}
}
impl PartialEq<Relaxed> for RBig {
#[inline]
fn eq(&self, other: &Relaxed) -> bool {
self.0.eq(&other.0)
}
}
impl PartialOrd<Relaxed> for RBig {
#[inline]
fn partial_cmp(&self, other: &Relaxed) -> Option<Ordering> {
self.0.partial_cmp(&other.0)
}
}