malachite_nz/natural/comparison/partial_cmp_primitive_float.rs
1// Copyright © 2026 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::natural::Natural;
10use core::cmp::Ordering::{self, *};
11use malachite_base::num::conversion::traits::{ExactFrom, IntegerMantissaAndExponent};
12use malachite_base::num::logic::traits::SignificantBits;
13
14macro_rules! impl_float {
15 ($t: ident) => {
16 impl PartialOrd<$t> for Natural {
17 /// Compares a [`Natural`] to a primitive float.
18 ///
19 /// # Worst-case complexity
20 /// $T(n) = O(n)$
21 ///
22 /// $M(n) = O(1)$
23 ///
24 /// where $T$ is time, $M$ is additional memory, and $n$ is `self.significant_bits()`.
25 ///
26 /// See [here](super::partial_cmp_primitive_float#partial_cmp).
27 fn partial_cmp(&self, other: &$t) -> Option<Ordering> {
28 if other.is_nan() {
29 None
30 } else if *other < 0.0 {
31 Some(Greater)
32 } else if !other.is_finite() {
33 Some(Less)
34 } else if *other == 0.0 {
35 self.partial_cmp(&0u32)
36 } else if *self == 0u32 {
37 Some(Less)
38 } else {
39 let (m, e) = other.integer_mantissa_and_exponent();
40 let log_cmp = i64::exact_from(self.significant_bits())
41 .cmp(&(i64::exact_from(m.significant_bits()) + e));
42 Some(if log_cmp != Equal {
43 log_cmp
44 } else {
45 self.cmp_normalized(&Natural::from(m))
46 })
47 }
48 }
49 }
50
51 impl PartialOrd<Natural> for $t {
52 /// Compares a primitive float to a [`Natural`].
53 ///
54 /// # Worst-case complexity
55 /// $T(n) = O(n)$
56 ///
57 /// $M(n) = O(1)$
58 ///
59 /// where $T$ is time, $M$ is additional memory, and $n$ is `other.significant_bits()`.
60 ///
61 /// See [here](super::partial_cmp_primitive_float#partial_cmp).
62 #[inline]
63 fn partial_cmp(&self, other: &Natural) -> Option<Ordering> {
64 other.partial_cmp(self).map(Ordering::reverse)
65 }
66 }
67 };
68}
69apply_to_primitive_floats!(impl_float);