Skip to content

Commit 97a2711

Browse files
jogru0mbrubeck
authored andcommitted
refactor float hashing code
1 parent 2c88765 commit 97a2711

File tree

1 file changed

+15
-19
lines changed

1 file changed

+15
-19
lines changed

src/lib.rs

Lines changed: 15 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -157,12 +157,15 @@ impl<T: Float> PartialEq<T> for OrderedFloat<T> {
157157

158158
impl<T: Float> Hash for OrderedFloat<T> {
159159
fn hash<H: Hasher>(&self, state: &mut H) {
160-
if self.is_nan() {
161-
// normalize to one representation of NaN
162-
hash_float(&T::nan(), state)
160+
let bits = if self.is_nan() {
161+
CANONICAL_NAN_BITS
162+
} else if self.is_zero() {
163+
CANONICAL_ZERO_BITS
163164
} else {
164-
hash_float(&self.0, state)
165-
}
165+
raw_double_bits(&self.0)
166+
};
167+
168+
bits.hash(state)
166169
}
167170
}
168171

@@ -1015,7 +1018,13 @@ impl<T: Float> Ord for NotNan<T> {
10151018
impl<T: Float> Hash for NotNan<T> {
10161019
#[inline]
10171020
fn hash<H: Hasher>(&self, state: &mut H) {
1018-
hash_float(&self.0, state)
1021+
let bits = if self.is_zero() {
1022+
CANONICAL_ZERO_BITS
1023+
} else {
1024+
raw_double_bits(&self.0)
1025+
};
1026+
1027+
bits.hash(state)
10191028
}
10201029
}
10211030

@@ -1350,22 +1359,9 @@ impl From<FloatIsNan> for std::io::Error {
13501359
}
13511360
}
13521361

1353-
#[inline]
1354-
fn hash_float<F: Float, H: Hasher>(f: &F, state: &mut H) {
1355-
raw_double_bits(f).hash(state);
1356-
}
1357-
13581362
#[inline]
13591363
fn raw_double_bits<F: Float>(f: &F) -> u64 {
1360-
if f.is_nan() {
1361-
return CANONICAL_NAN_BITS;
1362-
}
1363-
13641364
let (man, exp, sign) = f.integer_decode();
1365-
if man == 0 {
1366-
return CANONICAL_ZERO_BITS;
1367-
}
1368-
13691365
let exp_u64 = exp as u16 as u64;
13701366
let sign_u64 = (sign > 0) as u64;
13711367
(man & MAN_MASK) | ((exp_u64 << 52) & EXP_MASK) | ((sign_u64 << 63) & SIGN_MASK)

0 commit comments

Comments
 (0)