malachite_float/comparison/hash.rs
1// Copyright © 2025 Mikhail Hogrefe
2//
3// This file is part of Malachite.
4//
5// Malachite is free software: you can redistribute it and/or modify it under the terms of the GNU
6// Lesser General Public License (LGPL) as published by the Free Software Foundation; either version
7// 3 of the License, or (at your option) any later version. See <https://www.gnu.org/licenses/>.
8
9use crate::InnerFloat::{Finite, Infinity, NaN, Zero};
10use crate::{ComparableFloat, ComparableFloatRef, Float};
11use core::hash::{Hash, Hasher};
12
13impl Hash for ComparableFloat {
14 /// Computes a hash of a `ComparableFloat`.
15 ///
16 /// The hash is compatible with `ComparableFloat` equality: all `NaN`s hash to the same value.
17 ///
18 /// # Worst-case complexity
19 /// $T(n) = O(n)$
20 ///
21 /// $M(n) = O(1)$
22 ///
23 /// where $T$ is time, $M$ is additional memory, and $n$ is `self.significant_bits()`.
24 #[inline]
25 fn hash<H: Hasher>(&self, state: &mut H) {
26 self.as_ref().hash(state);
27 }
28}
29
30impl Hash for ComparableFloatRef<'_> {
31 /// Computes a hash of a `ComparableFloatRef`.
32 ///
33 /// The hash is compatible with `ComparableFloatRef` equality: all `NaN`s hash to the same
34 /// value.
35 ///
36 /// # Worst-case complexity
37 /// $T(n) = O(n)$
38 ///
39 /// $M(n) = O(1)$
40 ///
41 /// where $T$ is time, $M$ is additional memory, and $n$ is `self.significant_bits()`.
42 fn hash<H: Hasher>(&self, state: &mut H) {
43 match self.0 {
44 float_nan!() => "NaN".hash(state),
45 Float(Infinity { sign }) => {
46 if *sign {
47 "Infinity".hash(state);
48 } else {
49 "-Infinity".hash(state);
50 }
51 }
52 Float(Zero { sign }) => {
53 if *sign {
54 "0.0".hash(state);
55 } else {
56 "-0.0".hash(state);
57 }
58 }
59 Float(Finite {
60 sign,
61 exponent,
62 precision,
63 significand,
64 }) => {
65 sign.hash(state);
66 exponent.hash(state);
67 precision.hash(state);
68 significand.hash(state);
69 }
70 }
71 }
72}