2020-06-10 22:35:23 +00:00
|
|
|
use std::{
|
|
|
|
cmp::Ordering,
|
|
|
|
hash::{Hash, Hasher},
|
2020-06-24 18:35:01 +00:00
|
|
|
ops::Neg,
|
2020-06-10 22:35:23 +00:00
|
|
|
};
|
|
|
|
|
2021-03-11 00:27:30 +00:00
|
|
|
/// A wrapper type that enables ordering floats. This is a work around for the famous "rust float
|
|
|
|
/// ordering" problem. By using it, you acknowledge that sorting NaN is undefined according to spec.
|
|
|
|
/// This implementation treats NaN as the "smallest" float.
|
2020-06-10 22:35:23 +00:00
|
|
|
#[derive(Debug, Copy, Clone, PartialOrd)]
|
|
|
|
pub struct FloatOrd(pub f32);
|
|
|
|
|
2020-08-16 07:30:04 +00:00
|
|
|
#[allow(clippy::derive_ord_xor_partial_ord)]
|
2020-06-10 22:35:23 +00:00
|
|
|
impl Ord for FloatOrd {
|
|
|
|
fn cmp(&self, other: &Self) -> Ordering {
|
|
|
|
self.0.partial_cmp(&other.0).unwrap_or_else(|| {
|
|
|
|
if self.0.is_nan() && !other.0.is_nan() {
|
|
|
|
Ordering::Less
|
|
|
|
} else if !self.0.is_nan() && other.0.is_nan() {
|
|
|
|
Ordering::Greater
|
|
|
|
} else {
|
|
|
|
Ordering::Equal
|
|
|
|
}
|
|
|
|
})
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl PartialEq for FloatOrd {
|
|
|
|
fn eq(&self, other: &Self) -> bool {
|
|
|
|
if self.0.is_nan() && other.0.is_nan() {
|
|
|
|
true
|
|
|
|
} else {
|
|
|
|
self.0 == other.0
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl Eq for FloatOrd {}
|
|
|
|
|
|
|
|
impl Hash for FloatOrd {
|
|
|
|
fn hash<H: Hasher>(&self, state: &mut H) {
|
2020-10-03 19:56:25 +00:00
|
|
|
if self.0.is_nan() {
|
|
|
|
// Ensure all NaN representations hash to the same value
|
2022-04-27 18:02:05 +00:00
|
|
|
state.write(&f32::to_ne_bytes(f32::NAN));
|
2020-10-03 19:56:25 +00:00
|
|
|
} else if self.0 == 0.0 {
|
|
|
|
// Ensure both zeroes hash to the same value
|
2022-04-27 18:02:05 +00:00
|
|
|
state.write(&f32::to_ne_bytes(0.0f32));
|
2020-10-03 19:56:25 +00:00
|
|
|
} else {
|
2022-04-27 18:02:05 +00:00
|
|
|
state.write(&f32::to_ne_bytes(self.0));
|
2020-10-03 19:56:25 +00:00
|
|
|
}
|
2020-06-10 22:35:23 +00:00
|
|
|
}
|
|
|
|
}
|
2020-06-24 18:35:01 +00:00
|
|
|
|
|
|
|
impl Neg for FloatOrd {
|
|
|
|
type Output = FloatOrd;
|
2020-07-28 21:24:03 +00:00
|
|
|
|
2020-06-24 18:35:01 +00:00
|
|
|
fn neg(self) -> Self::Output {
|
|
|
|
FloatOrd(-self.0)
|
|
|
|
}
|
2020-07-10 08:37:06 +00:00
|
|
|
}
|