use super::GuardedF32;
use std::cmp::{Ordering, PartialEq, PartialOrd};
impl PartialEq for GuardedF32 {
fn eq(&self, other: &Self) -> bool {
self.0 == other.0
}
}
impl Eq for GuardedF32 {}
impl PartialEq<f32> for GuardedF32 {
fn eq(&self, other: &f32) -> bool {
other.is_finite() && self.0 == *other
}
}
impl PartialEq<GuardedF32> for f32 {
fn eq(&self, other: &GuardedF32) -> bool {
self.is_finite() && *self == other.0
}
}
impl PartialOrd for GuardedF32 {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl Ord for GuardedF32 {
fn cmp(&self, other: &Self) -> Ordering {
let lhs = self.0;
let rhs = other.0;
match (lhs < rhs, lhs > rhs) {
(true, _) => Ordering::Less,
(_, true) => Ordering::Greater,
_ => Ordering::Equal,
}
}
}
impl PartialOrd<f32> for GuardedF32 {
fn partial_cmp(&self, other: &f32) -> Option<Ordering> {
if other.is_finite() {
self.0.partial_cmp(other)
} else {
None
}
}
}
impl PartialOrd<GuardedF32> for f32 {
fn partial_cmp(&self, other: &GuardedF32) -> Option<Ordering> {
if self.is_finite() {
self.partial_cmp(&other.0)
} else {
None
}
}
}
#[cfg(test)]
mod tests {
use crate::{GuardedF32, f32::tests::valid_f32};
use proptest::prelude::*;
proptest! {
#[test]
fn test_valid_cmp_valid(a in valid_f32(), b in valid_f32()) {
let checked_a = GuardedF32::new(a).unwrap();
let checked_b = GuardedF32::new(b).unwrap();
prop_assert_eq!(checked_a > checked_b, a > b);
prop_assert_eq!(checked_a > b, a > b);
prop_assert_eq!(a > checked_b, a > b);
prop_assert_eq!(checked_a >= checked_b, a >= b);
prop_assert_eq!(checked_a < checked_b, a < b);
prop_assert_eq!(checked_a <= checked_b, a <= b);
prop_assert_eq!(checked_a.partial_cmp(&checked_b), a.partial_cmp(&b));
}
#[test]
fn test_valid_cmp_invalid(a in valid_f32(), b in valid_f32()) {
prop_assert_eq!(GuardedF32::new(a).unwrap() > GuardedF32::new(b).unwrap(), a > b);
prop_assert_eq!(GuardedF32::new(a).unwrap() >= GuardedF32::new(b).unwrap(), a >= b);
prop_assert_eq!(GuardedF32::new(a).unwrap() < GuardedF32::new(b).unwrap(), a < b);
prop_assert_eq!(GuardedF32::new(a).unwrap() <= GuardedF32::new(b).unwrap(), a <= b);
}
#[allow(clippy::float_cmp)]
#[test]
fn test_valid_eq_valid(a in valid_f32()) {
let checked_a = GuardedF32::new(a).unwrap();
prop_assert_eq!(checked_a, a);
prop_assert_eq!(a, checked_a);
prop_assert_eq!(checked_a, checked_a);
}
}
}